【发布时间】:2019-11-24 14:27:43
【问题描述】:
我正在尝试以反应式编程方式实现 CRUD 功能。我有一个表单,其中一个字段 identifier_name 必须是唯一的。
但是,在调用 create new 或 update 方法之前,我需要先检查我正在创建或更新的 identifier_name 字段的值是否已经存在于我的 observable 是这样的 observable 中。
this.userService.users$;
以下是我的组件中的代码。
@Component({...})
export class UserEditComponent implements OnInit, OnDestroy {
subscription: Subscription = new Subscription();
ngOnDestroy() {
this.subscription.unsubscribe();
}
saveUser(): void {
if (this.userForm.valid) {
this.identifierExists$.subscribe(exists => {
if (exists) {
this.snackBar.open('The scope identifier must be unique.', 'Close', { duration: 5000 });
} else {
if (this.isNewRecord) {
this.createNewUser();
} else {
this.updateUser();
}
}
})
} else {
this.snackBar.open("An error occured while saving your changes. Please try again.", "Close", { duration: 5000 });
}
}
createNewUser(): void {
this.subscription.add(
this.userService.saveUser(this.userForm.value)
.pipe(catchError(this.handleError))
.subscribe(() => {
this.snackBar.open('New user successfully created.', 'Close', { duration: 5000 });
})
)
}
updateUser(): void {
this.subscription.add(
this.userService.selectedUserIdAction$
.pipe(
switchMap(id => this.userService.updateUser(id, this.userForm.value))
)
.subscribe(_ => {
this.snackBar.open("User successfully updated.", "Close", { duration: 5000 })
})
)
}
}
我的想法是这样做。
private identifierSubject = new BehaviorSubject<string>('');
identifierAction$ = this.identifierSubject.asObservable();
identifierExists$ = this.identifierAction$.pipe(
switchMap(identifier => {
this.userService.users$
.pipe(
map(users => users.some(user => user.identifier_name === identifier))
)
})
)
我不确定这是否是满足我要求的正确方法,因为我对反应式编程的概念还很陌生。
另外,如果你注意到我的两种方法createNewUser() 和updateUser。有没有一种方法可以触发 create 和 update 而无需订阅?我在反应式编程中所知道的是避免subscribe。但是,不确定如何以正确的方式做到这一点。
希望您能指导我如何以反应式编程方式正确地做到这一点。
TIA
【问题讨论】:
标签: angular reactive-programming angular-reactive-forms rxjs6