繁体   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