首页 > 解决方案 > 无法使用订阅角度的结果

问题描述

我遵循本指南,并尝试在Unrelated Components: Sharing Data with a Service段落中做类似的事情

数据服务:

 @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);
  }

提前致谢

标签: javascriptangularcomponentsobserver-patternsubscribe

解决方案


和:

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简单地返回一个可观察的:

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

还记得clearIntervalOnDestroy

演示


推荐阅读