代码之家  ›  专栏  ›  技术社区  ›  Neekoy

从“getter”方法服务中的HttpGet请求获取结果

  •  0
  • Neekoy  · 技术社区  · 6 年前

    这可能是相当简单,但角度不完全是我的强项,它花了我一点时间比我预期的。我有一个调用外部API的服务,我想在应用程序初始化时获取变量,并在多个其他组件中使用它。

    我有以下服务:

    import { Injectable } from '@angular/core';
    import { HttpClient } from  '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class DatabaseConnectionService {
    
      API_URL: string = "http://localhost:4044";
    
      apiResult;
    
      constructor(private http: HttpClient) { 
        this.dbConn.getApiRoot()
        .subscribe(
          data => this.apiResult = { message: data['message'] }
        );
      }
    
      getApiRoot() { 
        return this.http.get<Apiroot[]>(this.API_URL);
      }
    
      returnApiResult() {
        return this.apiResult;
      }
    
    }
    

    returnApiResult() 获取变量的值,但它返回为空,因为它是可观察的(我认为应该已经赋值了,因为它在服务的构造函数中)。感谢您的帮助。

    1 回复  |  直到 6 年前
        1
  •  1
  •   user184994    6 年前

    在构造函数中,更改代码如下:

      import { shareReplay } from 'rxjs/operators';
    
      //...
    
      constructor(private http: HttpClient) { 
        this.apiResult = this.dbConn.getApiRot().pipe(shareReplay());
      }
    

    shareReplay

      this.service.apiResult.subscribe(() => console.log("Done"))
    

    但在应用程序加载时,服务只需加载一次数据