首页 > 解决方案 > 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())
}

标签: typescriptrxjs

解决方案


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))
    }
}

推荐阅读