Angular 是否强制订阅服务器从服务重新请求数据?
我有一个简单的结构,有多个组件和一个服务[]: 服务 @注射的 出口类服务{ 构造函数私有http:HttpClient{} 后实体:可观察性:可观察{ 返回此文件。http .post'/api/entity',entity .日期; } 获得:可观察{ 返回此文件。http .get“/api/entity” .日期; } } 组件0 @组成部分{ 选择器:“app-component0”, 模板:` `, 样式URL:[] } 导出类组件0{} 组件1 @组成部分{ 选择器:“app-component1-create”, 模板:`Submit`, 样式URL:[] } 导出类组件1{ 构造函数私有服务:服务{} 提交{ this.service.post{foo:'bar'} .subscribeconsole.info,console.error } } 组件2 @组成部分{ 选择器:“app-component2-table”, 模板:``, 样式URL:[] } 导出类Component2实现OnInit{ 实体:企业[]; 构造函数私有服务:服务{} 恩戈尼特{ 这是服务 .subscribeentities=>this.entities=实体, 控制台错误 } }Angular 是否强制订阅服务器从服务重新请求数据?,angular,typescript,rxjs,angular-services,angular-components,Angular,Typescript,Rxjs,Angular Services,Angular Components,我有一个简单的结构,有多个组件和一个服务[]: 服务 @注射的 出口类服务{ 构造函数私有http:HttpClient{} 后实体:可观察性:可观察{ 返回此文件。http .post'/api/entity',entity .日期; } 获得:可观察{ 返回此文件。http .get“/api/entity” .日期; } } 组件0 @组成部分{ 选择器:“app-component0”, 模板:` `, 样式URL:[] } 导出类组件0{} 组件1 @组成部分{ 选择器:“app-co
如何让Component1通过服务更新Component2?您应该有另一个可观察到的组件来缓解您的组件通信:
private _employes$ = new BehaviorSubject<{...}[]>([]);
由两部分组成:
当你想更新你的流时,你可以在它旁边观察到它
get employes$(): Observable<{...}[]> {
return this._employes$.asObservable();
}
暴露吸气剂。任何需要通过商店的任何更改通知的组件都可以订阅它
refresh() {
this._http.get<{...}[]>('...').subscribe(
data => this._employes$.next(data)
);
}
从现在起,一切都与您的实际情况有关,您有各种方法来更新此内部可观测值:
最快的方法:
在您的服务中,您订阅您的http调用并更新您的内部observable
赞成者:
您没有公开请求。
很容易维护,因为只有一个地方可以进行API调用。
反对:
不适用于您希望实际控制、更新。。。对API答案执行一些特定的操作。
订阅服务并不总是一个好主意。
可观察体操
如果你不想订阅你的服务。您可以执行以下操作:
refresh(myCustomTraitment: = null) {
return this._http.get<{...}[]>('...')
.pipe(switchMap(result => {
if (myCustomTraitment) {
result = result.map(myCustomTraitment);
}
this._employes$.next(result);
return this._employes$;
}));
}
您可以将http get OVERVABLE转换为内部可观察。同时,下一步将显示API答案的新结果
如果明天您需要在API响应上委派一项特殊任务,然后才能使其在应用程序中可用
你可以做:
您希望,无论何时在comp1上提交,也就是说,向与comp2的entities属性无关的数据库发送post请求,它都应该更新comp2上的entities,对吗?只添加了一个链接。是的,没错。这可能是因为我不打算拥有comp2的entities属性,可能是因为我在服务中存储了一些东西,可能是因为我使用了Behavior Subject或Subject而不是松散数组。如何以可维护的方式处理此常见场景?
return this._http.get<{...}[]>('...')
.pipe(switchMap(result => {
this._employes$.next(result);
return this.employes$;
}));
refresh(myCustomTraitment: = null) {
return this._http.get<{...}[]>('...')
.pipe(switchMap(result => {
if (myCustomTraitment) {
result = result.map(myCustomTraitment);
}
this._employes$.next(result);
return this._employes$;
}));
}