angular - HttpInterceptor 内部路由导航

标签 angular interceptor angular5

在 HttpInterceptor 中捕获到 401 错误时是否可以导航到特定路由?

我尝试做的是:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
​    return next.handle(req)
        .do((event: HttpEvent<any>) => {}, (error: any) => {
             if (error instanceof HttpErrorResponse) {
                 if (error.status === 401) {
                     this.router.navigate(['/signin']);
                 }
             }
         });
​}

但什么也没有发生。

只有使用我才能重定向到登录页面

window.location.href = '/signin';

代替

this.router.navigate(['/signin']);

最佳答案

是的,这是可能的,在 Angular 4 和 5 中尝试过。

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpRequest, HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import { AuthHelperService } from '../main/content/authentication/auth-helper.service';


@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {

    constructor(private authHelperService: AuthHelperService, private router: Router ) {}


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request)
            .do((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    // If required, here we can do any stuff with the response getting from API.
                    console.log('Common place to handle 1 response');
                }
            })
            .catch(error => {
                if (error instanceof HttpErrorResponse) {
                    if (error.status === 401) {
                        //when the API service return any 401-Unauthorized error control come here, 
                        //Call logoutUser to clear and redirect to login page. 
                        console.log('Handle 401');
                        this.authHelperService.logoutUser();
                        //this.router.navigate(['auth/login']); //You can Navigate to the router directly, in this example it will be done in authHelperService.
                    }

                    return Observable.throw(error);
                }else{
                    return Observable.throw(error);
                }
            });

    }

}

以下是服务代码,错误情况下一定要Resolve()否则会挂起状态:

getFaqs(): Promise<any[]>
{
    return new Promise((resolve, reject) => {

        const body = '';

        this.http.post('http://localhost:3000/faq/faqs', body)    
        //Map is a handler to parse the response, subscribe will get parsed value as the result. Error has been gloably handled, by HTTP Intercepter.
        .map((res:Response)=>res)  
        .subscribe(
            (result: any) => {
                //console.log('faq/faqs Service Response : ' + JSON.stringify(result));
                this.faqs = result.data;
                this.onFaqsChanged.next(this.faqs);
                resolve(this.faqs);        
            },
            (error)=>{
                console.log('ERROR CAME HERE');
                resolve();
            }
        );

    });
}

关于angular - HttpInterceptor 内部路由导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477018/

相关文章:

javascript - 无法动态推送数组值比较两个数组

android graphQL Apollo

css - 如何使用 Angular 5 基于其组件将特定类添加到导航栏

html - 使用 p-tableHeaderCheckbox 和 p-table 移动到下一页时,应取消选中标题中的“全选”复选框

angular - 使用 `--prod` 构建的 ionic 滚动头包问题(请添加 @NgModule 注释。)

html - Bootstrap 4 表格响应,水平和垂直滚动

json - 在 Angular 2 中使用 JSON 正文发出 POST 请求

angularjs - AngularJS 中的 401 未经授权的错误处理

javascript - 并排显示两个输入

http - 如何在 NestJS 中使用多个全局拦截器