Angular 5 HttpInterceptor流程

时间:2017-11-26 00:24:48

标签: angular angular-http-interceptors

我正在尝试在我的一个Angular应用程序中实现HttpInterceptor,以便在每个请求中显示spinner。微调器显示出漂亮。但是,我还实现了notificationService,它利用SweetAlert根据服务器的响应显示通知模式。我能够显示Success模态而不是Error模态。我的代码如下:

INTERCEPTOR:

 intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
 this._spinnerService.requestStarted();
 return next.handle(req).do(
   (event: HttpEvent<any>) => {
     if (event instanceof HttpResponse) {
       this._spinnerService.requestEnded();
     }
   },
   (err: any) => {
     if (err instanceof HttpErrorResponse) {
       this._spinnerService.requestEnded();
     }
   }
 );
}

LOGIN:

login() {
this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => {
  this.showSpinner = state;
});
   const user = {
     email: this.userEmail,
     password: this.userPw
   };

   this.authService.authenticateUser(user).subscribe((data: ILoginResponse) => {
     this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => {
        this.showSpinner = state;
     });
     if (data.success) {
      this.notificationService.showSuccess(data.title, data.message)
        .then((result) => {
          console.log(result);
          this.router.navigate(['/user/dashboard']);
        })
        .catch((reason) => {
          console.log('--> Alert dismissed: ', reason);
        });
     } else {
       this.notificationService.showError(data.title, data.message)
        .then((result) => {
          console.log(result);
        })
        .catch((reason) => {
          console.log('--> Error dismissed: ', reason);
        });
     }
   });
  }

通知服务:

  showSuccess(type, message) {
   return swal({
    title: 'Success',
    text: message,
    type: type
   });
  }

  showError(type, message) {
    return swal({
      title: 'Error',
      text: message,
      type: type
    });
  }

非常感谢任何帮助/建议。感谢。

编辑:我尝试将NotificationService,特别是showError()放在拦截器的(err:any)块中。它确实有效,但我希望NotificationService保留特定组件(如Login),而不是每个请求。

2 个答案:

答案 0 :(得分:1)

更改您的代码

login() {
    this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => {
        this.showSpinner = state;
    });
    const user = {
        email: this.userEmail,
        password: this.userPw
    };

    this.authService.authenticateUser(user).subscribe((data: ILoginResponse) => {
        this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => {
            this.showSpinner = state;
        });
        console.log('My data:', data);
        this.notificationService
            .showAlert(data.title, data.message, 'success', res => {
                console.log(res);
                this.router.navigate(['/user/dashboard']);
            });
    }, error => {
        console.log('My error:', error);
        this.notificationService
            .showAlert(err.title, err.message, 'error', res => {
                console.log(res);
            });
    });
}



showAlert(title: string, message: string, type: string, callback?: any) {
    return swal({
        title: title,
        text: message,
        type: type
    }).then(() => {
        if(callback) {
            callback(message);
        }
    });
}

答案 1 :(得分:0)

拦截器的流程是为了防止从RestAPI调用返回faulsy响应。

例如,在我上面的问题中,我检查了data.success,因为这是我在后端设置的方式。拦截器将确保您获得truthy响应,而归类为Error的任何内容都将设置为HttpErrorResponse

this.authService.authenticateUser(user).subscribe(
 (data: ILoginResponse) => {
 console.log(data);
 this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => {
    this.showSpinner = state;
 });
 this.notificationService.showSuccess(data.title, data.message)
    .then((result) => {
      console.log(result);
      this.router.navigate(['/user/dashboard']);
    })
    .catch((reason) => {
      console.log('--> Alert dismissed: ', reason);
    });
   },

   (err: any) => {
      console.log(err);
      this.notificationService.showError('error', 'Just an error'); <- my NotificationService will 
get called here instead of getting called up in the else block like in my question above.
    });
相关问题