【问题标题】:Angular 8 - Piping issue when dealing with an http returned observableAngular 8 - 处理 http 返回的 observable 时的管道问题
【发布时间】:2019-10-15 12:53:14
【问题描述】:

我正在尝试使用用于授权登录凭据的 http 请求做几件事。

首先,我尝试使用 navigateByUrl('/') 在成功登录/注册后将用户重定向回主页。

其次,我想将从服务器收到的错误传递给先前建立的空错误列表。

submitForm() {
     this.isSubmitting = true;
     this.errors = new Errors();

     let credentials = this.authForm.value;
     this.userService.attemptAuth(this.authType, credentials)
       .subscribe(
         data => this.router.navigateByUrl('/'),
         err => {
           this.errors = err;
           this.isSubmitting = false;
       }
     );
   }

我的想法是我不应该在 subscribe() 方法中包含我的两个箭头函数。我应该用管道代替这两个功能吗?我对如何在 pipe() 调用中使用 catchError() 有一个很好的想法,但是对于如何在 pipe() 中执行 url 重定向有点不清楚。

任何建议将不胜感激,谢谢!

【问题讨论】:

  • 不需要管道,你的实现应该可以工作,this.isSubmitting = false;也需要在数据部分,因为您想表明提交已完成。

标签: javascript angular redirect error-handling pipe


【解决方案1】:

尝试回答您最初的问题:如果您想在管道上导航,您可以执行以下操作:

submitForm() {
    this.isSubmitting = true;
    this.errors = new Errors();

    let credentials = this.authForm.value;
    this.userService.attemptAuth(this.authType, credentials)
        .pipe(
            tap(() => this.router.navigateByUrl('/'))
        )
        .subscribe(
            (data) => {
                this.isSubmitting = false;
            },
            (error) => {
                this.errors = error;
                this.isSubmitting = false;
            }
        );
}

我不鼓励这样做,因为它只会为您已经可以在 subscribe() 中执行的操作增加更多开销;

【讨论】:

    猜你喜欢
    • 2019-12-07
    • 2017-11-30
    • 2021-11-14
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多