iT邦幫忙

0

angular 中用 subject (BehaviorSubject 要如何接到資料變化?)

請問 BehaviorSubject 如何接收最新的資料?
舉例說,在 service 中用 httpclient get 所有訂單資料,用 Observable接收

  // service
  public orderDataSubject = new BehaviorSubject<order[]>([]);
  public orderData = this.orderDataSubject.asObservable();
  constructor(
    private httpClient: HttpClient) {}
    
  getList(): Observable<order[]> {
    this.httpClient
      .post<any>('/api/order/getAll', body)
      .subscribe(data => {
        this.flowDataSubject.next(data);
      });
  }

接著,有3個 component: component1 中show 出訂單清單,component2 中show 總筆數。component3 中 show 明細,另外會有 增/刪/修 的動作。這3個 component 都要訂閱 orderData

  // component
  orderData: Observable<order[]>;
  constructor(
    private orderService: OrderService,
  ) {
    this.orderData = this.orderService.orderData;
  }
  
  ngOnInit() {
    this.orderService.getList();
  }

那麼,在 component 3 中做的增/刪的動作,在實際寫入資料庫成功後,執行 getList(),這時另外2個component 會接收到最新的 list嗎? 或說,要怎樣才能 update orderList 的內容?

Brandon iT邦新手 4 級 ‧ 2019-12-01 17:17:57 檢舉
剛剛 google 到 這一篇
(https://coryrylan.com/blog/angular-observable-data-services)
,似乎有回答到我的問題:

找個時間來試試
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答