簡體   English   中英

無法使用訂閱角度的結果

[英]Can't use result from subscribe angular

我遵循指南,並嘗試在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);
  }
  • 使用此代碼,我在handleVarChange日志中得到了“未定義”

  • 而不是調用this.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只是返回一個可觀察的:

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

還記得在OnDestroy clearInterval OnDestroy

演示

省略handleVarChange.data

代替

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM