簡體   English   中英

Angular 2訂閱組件或服務?

[英]Angular 2 subscribe from component or service?

上下文

我有一個組件HospitalComponent ,試圖顯示醫院列表。 它使用來自HospitalServicereadAll方法(從readAll返回一個Observable):

ngOnInit() {
  this.hospitalService
    .readAll() // Make a firebase call
    .subscribe(hospitals => this.hospitals = hospitals);
}

路線/hospital插入此組件HospitalComponent 每次我到/hospital ,角2作出新HospitalComponent ,一個新的呼叫到由hospitalService

問題

每次到達/hospital ,醫院名單都會延遲顯示。

從服務構造函數本身檢索醫院列表是一種好習慣嗎? 這樣,我可以從后台管理刷新列表,而不是有一些延遲。 我會在組件中:

ngOnInit() {
  this.hospitals = this.hospitalService.readAll();
}

並在服務中:

constructor(private hospitalService: HospitalService) {
  hospitalService.subscribe(hospitals => this.hospitals = hospitals);
}

但這意味着要手動管理所有醫院的變化。

從技術角度來看,兩種“解決方案”都非常相同 - 因為如果您只是想考慮兩種解決方案,它們基本上會做同樣的事情,這取決於您的個人品味。

但總的來說:盡量避免手動訂閱

有幾件事你可以改進(以下代碼是基於這樣的假設,你寧願顯示一個過時的列表,在后台更新,而不是顯示加載指示器):

  • 盡量避免手動訂閱(尤其是組件中的(!!)) - >使用async -pipe代替
  • 盡量避免使用有狀態組件(如果可能的話,甚至是服務) - >使用流來代替

你的服務

export class HospitalService {
    allHospitals$: BehaviorSubject<IHospital[]> = new BehaviorSubject<IHospital[]>([]);

    // the fetchAll() method can be called in the constructor, or somewhere else in the application e.g. during startup, this depends on your application-flow, maybe some login is required ect...
    fetchAll(): Observable<IHospital[]> {
        const fetch$: Observable<IHospital[]> = ...get_stuff_from_firebase().share();
        fetch$
            .do(allHospitals => this.allHospitals$.next(allHospitals);
            .subscribe();
        return fetch$; // optional, just in case you'd want to do something with the immediate result(or error) outside the service
    }
}

你的組件(=>只是注入服務)

constructor(private hospitalService: HospitalService) {
    // nothing to do here
}

組件的模板(=> async-pipe自動管理訂閱並自動取消訂閱,因此您不必擔心內存泄漏等...)

<div *ngFor="let hospital of (hospitalService.allHospitals$ | async)">
    {{hospital.name}}
</div>

第四個(但更加擴展的)解決方案是使用像ngrx這樣的中央商店 - 所以使用ngrx基本上所有醫院的部分allHospitals$將被轉移到集中管理的商店模塊,你會嚴格划分你的應用程序,這樣一來服務除了獲取和處理數據之外什么也不做,商店除了存儲和發送數據之外什么都不做, 除了顯示數據之外,組件什么都不做。

暫無
暫無

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

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