角度8拦截消息重定向

问题描述 投票:0回答:2

下面的代码显示了一个拦截器。当状态码为401时,我要将用户重定向到登录屏幕,并显示一条消息“密码或用户名无效”。我该如何实现?

由于如果将用户引导到登录屏幕,是否会调用“ return throwError”?而且,有没有办法对此进行测试?

拦截器:

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {

            let errorMessage = '';

            if(err instanceof HttpErrorResponse) { // server side error

                switch (err.status) {
                    case 401:      //login
                        errorMessage = `Username or password not found`;
                        this.authenticationService.logout(); // removes session data (if there are any)
                        this.router.navigate(['/login']);
                        break;          
            }
            return throwError(errorMessage);
        }
    }
  ))
}

LoginServiceMethod:

  login(username: string, password: string): Observable<any> {
return this.http.post<User>(`https://test/login`, { username, password })
    .pipe(
      map(user => {
        // store user details and jwt token in local storage to keep user logged in between page refreshes
        localStorage.setItem('currentUser', JSON.stringify(user));
        this.currentUserSubject.next(user);
        this.toast.success(user.username + ' logged in');
        return user;
    }));

}

ComponentLoginMethod:

    this.authenticationService.login(username, password)
.pipe(first())
.subscribe(
      data => {
          this.router.navigate([this.returnUrl]);
      },
      error => {
        console.error("blabla" + error);
      }
    );
}
angular http authentication interceptor
2个回答
0
投票
this.router.navigate(['/login'], { queryParams: { message: 'Invalid username/password' } });

然后在登录组件中检索查询参数OnInit


0
投票
this.router.navigate(['/login'], { state: { errorMessage: errorMessage } });

并从历史记录中获取错误消息

history.state.errorMessage
© www.soinside.com 2019 - 2024. All rights reserved.