无法使用订阅 angular 的结果

Can't use result from subscribe angular

我遵循 this 指南,并尝试在 不相关的组件:与服务共享数据 段落

中做类似的事情

数据服务:

 @Injectable()
export class MyDataService{

  private messageSource = new BehaviorSubject(null);
  currentMessage = this.messageSource.asObservable();

  constructor(private http: HttpClient) {
    setInterval(() => { this.changeMessage(this.resultFromRestCall()); }, 10 * 1000);
  }

  changeMessage(message: object) {
    this.messageSource.next(message);
  }

  resultFromRestCall(){
    const json;
    this.http.get<object>(myApiUrl).subscribe(res => 
       json['data'] = res['data'] //this is an example
    );
    return json;
  }

分量:

export class MyComponent implements OnInit {

  constructor(private dataservice: MyDataService) {}

  ngOnInit() {
    this.dataservice.currentMessage.subscribe(
      message => {this.handleVarChange(message); }
    );
  }

  handleVarChange(message) {
    console.log(message.data);
  }

提前致谢

省略handleVarChange中的.data:

而不是

handleVarChange(message) {
  console.log(message.data);
}

handleVarChange(message) {
  console.log(message);
}

有:

resultFromRestCall(){
  const json;
  this.http.get<object>(myApiUrl).subscribe(res => 
     // takes x amount of time to populate json
     json['data'] = res['data'] //this is an example
  );
 // executed instantly after above request has been called 
 return json;
}

您返回 json 之前 它已被填充,因为请求是异步的。

相反,你可以稍微翻转一下,先调用 resultFromRestCall(),当你得到响应时,然后 调用 changeMessage():

setInterval(() => { 
  this.resultFromRestCall().subscribe((data) => {
    this.changeMessage(data);
  });
}, 10 * 1000);

其中 resultFromRestCall 只是 returns 一个可观察的:

resultFromRestCall(){
  return this.http.get<object>(myApiUrl);
}

也记得在OnDestroyclearInterval

DEMO