每当您在服务中看到订阅时,代码可能有问题。你需要使用
.tap()
做一些副作用的操作。从不订阅服务,让组件处理订阅。
在职:
addLanguage(service: Service) {
const url = `${this.servicesUrl}/${service._id}/languages`;
const accessToken = this.authQuery.getSnapshot().accessToken;
this.http.post<Service>(url, service, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': accessToken
})
})
.pipe(
tap((entity: Service) => {
if (this.servicesQuery.hasEntity(service._id)) {
this.servicesStore.update(service._id, entity);
}
})
);
}
但是,在组件中,可以使用
filter()
和A
switchMap()
从
rxjs
. 的诀窍
forEach
,是你用的吗?
.map()
来自本机javascript数组函数。在你创建了这样的观察数组之后,你可以使用
forkJoin()
要组合它们并使它们平行发射:
组件中:
private addLanguage(languageForm: FormGroup) {
this.usersService.addLanguage(user).pipe(
takeUntil(this.ngUnsubscribe),
//filter away the conditions
filter((entity: User) => entity.userInfo.services),
switchMap((entity: User) => {
//use .map() to create an array of services.
let serviceObs$ = entity.UserInfo.services.map(serviceId =>
this.servicesService.addLanguage(createService({
_id: serviceId,
serviceInfo: {
userLanguages: [language]
}
})));
//use forkJoin to combine all of them
return forkJoin(serviceObs$);
})
).subscribe(() => {
languageForm.reset();
this.onNavigateBack();
}
);
}