簡體   English   中英

如何檢查Angular中是否填充了Observable值?

[英]How do I check if an Observable value is populated in Angular?

我希望通過單個HTTP請求將一些數據集中加載到應用程序中,並希望將此數據傳遞到多個單獨的組件。 我正在使用BehaviourSubject類來設置加載到共享服務中可觀察對象中的數據,並在各個組件中訂閱它。

SharedService:

  data: Observable<any>;

  load_data(){
  this.http.post('/myAPIMethod', {myInputs}).subscribe(
      res => {
              var dataSource=new BehaviorSubject(res);
              this.data = dataSource.asObservable();
          }, error => {
          console.log(error);
      });
  }

app.component.ts:

constructor(private shared: SharedService) { }
ngOnInit(){
  this.shared.load_data();
  }

myComponent.component.ts

constructor(private shared: SharedService) { }
ngAfterViewInit(){
  this.shared.data.subscribe(
      res => {console.log(res)},
      err => {console.log(err)}
    );
}

由於我的app.component.ts和myComponent.component.ts文件是異步且獨立地加載的,因此即使在應用程序加載數據之前,它嘗試訂閱myComponent中的“數據” Observable時,也會收到錯誤消息。 我訂閱了未定義的錯誤(“數據”未定義,並且已經在嘗試訂閱)。

在myComponent文件中訂閱之前,如何檢查“數據”可觀察值的設置?

改用Subject

data = new Subject();

load_data(){
  this.http.post('/myAPIMethod', {myInputs}).subscribe(
      res => {
              this.data.next(res);
          }, error => {
          console.log(error);
      });
}

這樣,您的組件可以在返回數據之前訂閱Subject ,並且在收到http調用時會發出數據。

此外,如果您不打算在訂閱函數中操作DOM / View元素,請在ngOnInit調用它:yourComponet.ts

ngOnInit(){
  this.shared.data.subscribe(
      res => {console.log(res)},
      err => {console.log(err)}
    );

暫無
暫無

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

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