我想以一种形式添加一本书。
用户手动输入作者的姓名。当用户提交表单时,应首先检查作者是否存在:
我想我可以让它发挥作用:
formSubmit() {
this.authorService.getByName(this.authorName).subscribe(author => {
// Author exists
if (author.id) {
this.book.author = author;
this.bookService.add(this.book).subscribe(() => {
// Book added
});
} else {
const authorObj: AuthorInterface = {
fullName = this.authorName;
}
this.authorService.add(authorObj); subscribe(author => {
this.book.author = author;
this.bookService.add(this.book).subscribe(() => {
// Book added
});
})
}
});
}但是这真的很可怕,我相信我可以用rxjs让它变得更干净,但却找不到解决方案。我对如何使用所有这些功能感到有点困惑。
我会感谢你的帮助。非常感谢:)
发布于 2020-11-12 00:25:30
如果这是一个很大的可观测值(许多已发出的值),您最好还是呆在
this.authorService
.getByName(this.authorName)
.pipe(
mergeMap((author: any) => {
if (author.id) {
this.book.author = author;
return this.bookService.add(this.book).pipe(
tap(() => {
console.log("book added");
})
);
} else {
const authorObj: AuthorInterface = {
fullName: this.authorName
};
return this.authorService.add(authorObj).pipe(
mergeMap((author: any) => {
this.book.author = author;
return this.bookService.add(this.book).pipe(
tap(() => {
console.log("book added");
})
);
})
);
}
})
)
.subscribe(() => console.log("job done"));或者,您也可以这样做:
const firstObservable = this.authorService.getByName(this.authorName).pipe(
filter((author: any) => author.id != null),
mergeMap(author => {
this.book.author = author;
return this.bookService.add(this.book).pipe(
tap(() => {
console.log("book added");
})
);
})
);
const secondObservable = this.authorService.getByName(this.authorName).pipe(
filter((author: any) => author.id == null),
mergeMap((author: any) => {
const authorObj: AuthorInterface = {
fullName: this.authorName
};
return this.authorService.add(authorObj).pipe(
mergeMap((author: any) => {
this.book.author = author;
return this.bookService.add(this.book).pipe(
tap(() => {
console.log("book added");
})
);
})
);
})
);
merge(firstObservable, secondObservable).subscribe(author =>
console.log("job done")
);发布于 2020-11-11 22:39:49
您可以使用switchMap。此运算符订阅另一个可观察到的传递给它的操作符并输出其结果。
this.authorService.getByName(this.authorName)
.pipe(
switchMap(author => {
if (author.id) {
this.book.author = author;
return this.bookService.add(this.book).pipe(...);
}
return this.authorService.add(authorObj).pipe(
switchMap(author => ...)
);
})
)
.subscribe();https://stackoverflow.com/questions/64794926
复制相似问题