无法使用订阅角度的结果

时间:2019-02-01 14:43:32

标签: javascript angular components observer-pattern subscribe

我遵循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日志中得到了“未定义”

  • 我没有在订阅中调用this.handleVarChange(message);,而是编写console.log(message)我正确地得到了结果。

  • 所以,我的问题是,是否有可能在组件的某些功能中使用来自数据服务的值。

预先感谢

2 个答案:

答案 0 :(得分:1)

使用:

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

DEMO

答案 1 :(得分:0)

.data中省略handleVarChange

代替

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

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