簡體   English   中英

Observable/BehaviorSubject 在 Angular 的不同模塊中不起作用

[英]Observable/BehaviorSubject not working in different modules of Angular

我有 1 個功能模塊( Fund module )在其組件之一中顯示基金數據,還有一個顯示顧問數據的AppModule 基金數據和顧問數據是一對多的關系。 Fund 組件從 AppModule 中定義的服務中獲取數據。

使用BehaviorSubject將數據傳遞給 Fund 模塊,因為如果用戶更新或修改 AppModule 中的數據,數據可能會發生變化。 訂閱的數據無法正常工作。 基金模塊僅顯示初始化BehaviorSubject的值 ( 10 )。 它不顯示更新的值 ( 100 ),訂閱也不能正常工作以第二次顯示這些值。

這是代碼:

AppModule 中的服務

test = new BehaviorSubject<number>(10);

getTest(): Observable<number> {
  return this.test.asObservable();
}

public updateLocalData(sleeves: Sleeve[]): void {
  .... update logic
  this.test.next(100);
}

Fund 模塊中的 FundDataComponent

changeDetection: ChangeDetectionStrategy.OnPush,

   ngOnInit(): void {
    this.test = this.service.getTest().subscribe((number) => {
      this.number = number;
      console.log(number);    // get's called only once to display 10
    });
  }

創建一個 model - resource.ts:

import { BehaviorSubject, Observable } from 'rxjs';
import { refCount, publishReplay } from 'rxjs/operators';

export class StreamResource {
   private loading = false;
   private behaviorSubject: BehaviorSubject<any>;
   public readonly obs: Observable<any>;

   constructor(defaultValue?: any) {
       this.behaviorSubject = new BehaviorSubject(defaultValue);
       this.obs = this.behaviorSubject.asObservable().pipe(publishReplay(1), refCount());
   }

   request(method: any): void {
       if (method && !this.loading) {
           this.loading = true;
           method().toPromise().then((data: any) => {
               if (data) { this.update(data); }
               this.loading = false;
           });
       }
   }

   getValue() {
       return this.behaviorSubject.getValue();
   }

   update(data: any) {
       this.behaviorSubject.next(data);
   }

   refresh() {
       const data = this.getValue();
       if (data) { this.update(data); }
   }
}

創建流服務

import { StreamResource } from '../models/resource';
public test = new StreamResource(10);

...

getTest() {
    this.test.request(() => this.testService.getTest());
}

如何使用?

  constructor(private streamService: StreamService) { }

  ngOnInit() {
    this.streamService.test.obs.subscribe((data: any) => {
      if (!data) {
        return this.streamService.getTest();
      } else {
        this.test = data;
      }
    });

暫無
暫無

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

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