typescript - How to chain the result of observable to the below observable in rxjs
问题描述
I am saving user in the database.
Here are the steps I am following
1) Validating the request.
2) hashing the password.
3) then storing the user details in users collection with the hashed password.
So below I have the code in which I am subscribing to hashPassword
method, once I get the hashed string, creating the user with the hashed string. subscribing to save
method and assigning the result to the observer's next method.
How can I do this zip()
or map()
operator instead of subscribing again and again.
createUser(req: Request, res: Response): Observable<mongoose.Document> {
const body = req.body
const self = this
return singleObservable(Observable.create((observer: Observer<mongoose.Document>) => {
const errorMessage = new UserValidator(req).validateRequest()
if (errorMessage) {
observer.error(errorMessage)
} else {
self.hashPassword(req.body.password).subscribe(new BaseObserver(
(value) => {
const newUser = new this.userModule({ email: req.body.email, username: req.body.username, password: value })
this.save(newUser).subscribe(new BaseObserver((value) => {
observer.next(value)
}, (err) => {
observer.error(err)
}))
}, (error) => observer.error(error)))
}
}))
}
private hashPassword(password: string): Observable<string> {
return singleObservable(Observable.create((observer: Observer<string>) => {
bcrypt.hash(password, 10, (err, result) => {
result.length > 0 ? observer.next(result) : observer.error(err)
})
}))
}
save<T extends mongoose.Document>(model: mongoose.Document): Observable<T> {
return singleObservable(Observable.create(function (observer: Observer<mongoose.Document>) {
model.save(function (err, object) {
emitResult(observer, object, err)
})
}))
}
emitResult<T, E>(observer: Observer<T>, result: T | null, err: E) {
result ? observer.next(result) : observer.error(err);
}
singleObservable<T>(observable: Observable<T>) : Observable<T> {
return observable.pipe(first())
}
解决方案
flatMap
我使用运算符解决了我的问题
createUser(req: Request, res: Response): Observable<mongoose.Document> {
const body = req.body
const self = this
const errorMessage = new UserValidator(req).validateRequest()
if (errorMessage) {
return throwError(errorMessage)
} else {
return self.hashPassword(req.body.password)
.pipe(flatMap((hashedString) => {
const newUser = new this.userModule({ email: req.body.email, username: req.body.username, password: hashedString })
return this.save(newUser)
}), catchError((err) => throwError(err))
}
}
推荐阅读
- fonts - Latex 为header定义中文字体样式
- python - 使用条件和函数向量化嵌套循环
- string - 将字符串转换为日期格式 - SAP Crystal Reports
- libvlc - vlcj 4.2.0 MediaPlayer.media().play() 或 mediaListPlayer.controls().play() 在 linux docker 容器中引发致命错误
- sql - Oracle:显示最小和最大连续代码但添加校验位
- reactjs - 在 React 中重新渲染时添加过渡
- c++ - 如何为父类和派生类使用一个变量
- c++ - 大小为 4*2 和 2*4 的两个矩阵的矩阵乘法
- python - 遵循 Heroku Python 教程时出现 TemplateSyntaxError
- assembly - 如何在 AT&T Assembly 中按字符将字符串复制到另一个字符串 char 中?