Angular-嵌套订阅处理错误处理 - 链多个api calls

发布于 2025-02-11 04:37:18 字数 1784 浏览 2 评论 0原文

我正在构建一个具有登录/注册流的角度应用程序,并且ATM我正在寻找一种简单,更可读的方法来编码以下内容:

register() {
    this.accountService.register(this.user, this.password, this.passwordConfirmation).subscribe(() => {
        this.accountService.login(this.user.email, this.password).subscribe((loginResult) => {
            this.accountService.csrfRefresh().subscribe(() => {
                if (loginResult.status === ELoginStatus.success) {
                    this.router.navigateByUrl(this.returnUrl);
                } else {
                    this.errorMessage$.next('Login unsuccessful');
                }
            }, () => {
                this.errorMessage$.next('Login unsuccessful');
            })
        }, () => {
            this.errorMessage$.next('Login unsuccessful');
        })
    }, () => {
        this.errorMessage$.next('Login unsuccessful');
    });
}

使用此代码,我需要编写4次错误处理代码,或创建单独的代码方法,或将数据传递到caping ubibject。这似乎很迟钝。

我一直在考虑使用等待

async register() {
    try {
        await this.accountService.register(this.user, this.password, this.passwordConfirmation).toPromise();
        const loginResult = await this.accountService.login(this.user.email, this.password).toPromise();
        await this.accountService.csrfRefresh().toPromise();

        // TS2532: Object is possibly 'undefined'
        if (loginResult!.status === ELoginStatus.success) {
            this.router.navigateByUrl(this.returnUrl);
        } else {
            this.errorMessage$.next('Login unsuccessful');
        }
    } catch (exception) {
        this.errorMessage$.next('Login unsuccessful');
    }
}

这要好得多,但是我希望避免async/等待,并且需要使用。 topromise()在可观测值上。

链接这3个API通话的推荐方法是什么?

I'm building an angular app with a login/registration flow, and ATM I'm looking for an easy and more readable way to code the following:

register() {
    this.accountService.register(this.user, this.password, this.passwordConfirmation).subscribe(() => {
        this.accountService.login(this.user.email, this.password).subscribe((loginResult) => {
            this.accountService.csrfRefresh().subscribe(() => {
                if (loginResult.status === ELoginStatus.success) {
                    this.router.navigateByUrl(this.returnUrl);
                } else {
                    this.errorMessage$.next('Login unsuccessful');
                }
            }, () => {
                this.errorMessage$.next('Login unsuccessful');
            })
        }, () => {
            this.errorMessage$.next('Login unsuccessful');
        })
    }, () => {
        this.errorMessage$.next('Login unsuccessful');
    });
}

With this code I need to write the error handling code 4 times, or create a seperate method, or pass data on to a BehaviorSubject. This seems to be sluggish.

Something I've been considering is to use await:

async register() {
    try {
        await this.accountService.register(this.user, this.password, this.passwordConfirmation).toPromise();
        const loginResult = await this.accountService.login(this.user.email, this.password).toPromise();
        await this.accountService.csrfRefresh().toPromise();

        // TS2532: Object is possibly 'undefined'
        if (loginResult!.status === ELoginStatus.success) {
            this.router.navigateByUrl(this.returnUrl);
        } else {
            this.errorMessage$.next('Login unsuccessful');
        }
    } catch (exception) {
        this.errorMessage$.next('Login unsuccessful');
    }
}

This is a lot better, but I was hoping to avoid async/await, and the need to use .toPromise() on Observables.

What's the recommended way to chain these 3 api-calls?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫尐诺 2025-02-18 04:37:18

您应该能够以更惯用的rxjs方式重写此逻辑

register() {
    this.accountService.register(this.user, this.password, this.passwordConfirmation).pipe(
      concatMap(() => this.accountService.login(this.user.email, this.password)),
      concatMap((loginResult) => {
        if (loginResult.status === ELoginStatus.success) {
           return this.router.navigateByUrl(this.returnUrl)
        }
        throw new Error("Login unsuccessful")
      })
    )
    .subscribe({
      next: data => {
            // process any result in case of success
            },
      error: () => this.errorMessage$.next('Login unsuccessful')
    })
}

,因为您需要在需要concatmap时使用concatmap,因为concatmap,意味着我们要等待上一个呼叫的响应,然后再移至第二个。

是正确的操作员,如果我们想在新请求中“杀死飞行请求”。

switchmap 它带有其自身的复杂性

You should be able to re-write this logic in a more idiomatic rxjs way like this

register() {
    this.accountService.register(this.user, this.password, this.passwordConfirmation).pipe(
      concatMap(() => this.accountService.login(this.user.email, this.password)),
      concatMap((loginResult) => {
        if (loginResult.status === ELoginStatus.success) {
           return this.router.navigateByUrl(this.returnUrl)
        }
        throw new Error("Login unsuccessful")
      })
    )
    .subscribe({
      next: data => {
            // process any result in case of success
            },
      error: () => this.errorMessage$.next('Login unsuccessful')
    })
}

As you see i tend to use concatMap when i need to compose more than one call to http, since concatMap implies that we wait for the response of the previous call before we move to the second.

switchMap is the right operator if we want to "kill on fly requests' when new requests come in.

mergeMap should be used when you want to manage more requests in parallel, but it comes with its own complexities.

Maybe you can find some inspiration here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文