Angular 从“中的HttpGet请求获取结果”;“吸气剂”;方法7服务

Angular 从“中的HttpGet请求获取结果”;“吸气剂”;方法7服务,angular,angular7,Angular,Angular7,这可能很简单,但角度并不是我的强项,它花费的时间比我预期的要多。我有一个调用外部API的服务,我想在应用程序初始化时获取变量,并在多个其他组件中使用它 我有以下服务: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DatabaseConnection

这可能很简单,但角度并不是我的强项,它花费的时间比我预期的要多。我有一个调用外部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;
  }

}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient};
@注射的({
providedIn:'根'
})
导出类数据库连接服务{
API_URL:字符串=”http://localhost:4044";
结果;
构造函数(专用http:HttpClient){
this.dbConn.getApiRoot()
.订阅(
data=>this.apireult={message:data['message']}
);
}
getApiRoot(){
返回this.http.get(this.API\uURL);
}
returnapisresult(){
返回此结果;
}
}

在任何其他组件中,我都需要能够调用
returnapireult()
并获取变量的值,但它返回为空,因为它是可观察的(我认为应该已经分配了,因为它在服务的构造函数中)。非常感谢您的帮助。

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

  import { shareReplay } from 'rxjs/operators';

  //...

  constructor(private http: HttpClient) { 
    this.apiResult = this.dbConn.getApiRot().pipe(shareReplay());
  }
通过使用操作符,它将在多个订阅者之间共享结果,并重播结果。这样,您的组件仍然可以订阅:

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

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

因为您启动了调用构造函数,所以没有必要获取响应数据。即使数据在构造函数中,它也是异步的,所以不能保证在调用
returnapireult
时已完成加载。相反,您应该返回实际的可观察对象,并在需要的组件中调用
subscribe
it@user184994是的,它是这样工作的,我有点希望初始化应用程序加载上的所有数据,然后通过组件访问它。这样也可以最大限度地减少API请求。您使用的是什么版本的rxjs?完美-它做到了这一点,并且在其他组件中只留下一行逻辑,这正是我想要的。我认为值得一提的是,last()包含在“import{last}from'rxjs/operators';”中,除了这是正确的答案之外。谢谢:)不确定如果有多个组件订阅数据,这只会加载数据一次。@AviadP刚刚玩过这个,你完全正确,我错了@Neekoy我已更改为使用
shareReplay
而不是
last
,这应该会更有效。请改用那个