【发布时间】:2021-01-29 13:05:28
【问题描述】:
我有以下代码可以正常工作。我想要的是将 getSaveObs 函数转换为箭头函数,以便我可以在保存函数中使用它。
private save(property: IProperty): void {
// I want the getSaveObs logic to be moved here instead of a separate function
this.getSaveObs(property)
.subscribe(savedProperty => {
this.property = savedProperty;
this.propertyStorageService.storeProperty(this.property);
this.propertyDetailsForm.get('id').setValue(this.property.id);
// if new property, move to step 2
if (!savedProperty.id) {
console.log('New property, moving to step 2');
if (this.clientId) {
this.router.navigateByUrl('/clients/' + this.clientId + '/properties/' + this.property.id + '/' + '2');
} else {
this.router.navigate(['/properties', this.property.id, '2']);
}
}
}, error => (console.error('Error adding/updating a property: ', error)));
}
private getSaveObs(property: IProperty): Observable<IProperty> {
if (property.id) {
if (this.clientId) {
return this.clientPropertiesService.updateProperty(this.accountService.userIdentity.userId,
this.clientId, property);
} else {
return this.profileService.updateProperty(this.accountService.userIdentity.userId, property);
}
} else {
// New property observable
if (this.clientId) {
return this.clientPropertiesService.createProperty(this.accountService.userIdentity.userId,
this.clientId, property);
} else {
return this.profileService.createProperty(this.accountService.userIdentity.userId, property);
}
}
}
这是返回 Observable 的调用方法之一
createUserProperty(property: IProperty, userDocument:
AngularFirestoreCollection): EntityResponseType {
delete property.id;
property.modifiedTs = firebase.firestore.Timestamp.now();
property.createdTs = firebase.firestore.Timestamp.now();
return from(userDocument.add(property))
.pipe(
map(res => {
return {...property, id: res.id};
})
);
}
【问题讨论】:
-
Observables 允许你的代码在任何时候监听
getSaveObs。您想保留该功能还是只需要运行该功能并等待结果? -
我正在使用 firebase 来存储数据,create/update 方法使用 from(....) 将 firebase 承诺转换为可观察的。我不确定这是否是最好的方法。我更新了描述以显示返回 observable 的方法之一。
标签: javascript angular typescript rxjs observable