![](/img/trans.png)
[英]How to test a function that returns an arrow function with Jest?
[英]How to convert a function that returns an observable to an arrow function?
我有以下代碼可以正常工作。 我想要的是將 getSaveObs function 轉換為箭頭 function,這樣我就可以在存檔 function 中使用它。
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};
})
);
}
為什么您認為箭頭 function 可以用於save(property: IProperty): void
而普通的 function 不能? 你想做什么?
不管任何 function 都可以像這樣變成箭頭 function
function someName(arg: ArgType): ReturnType {
/*...function body...*/
}
成為
const someName = (arg: ArgType): ReturnType => {
/*...function body...*/
}
所以在你的情況下,那是:
const 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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.