在HttpInterceptor中路由导航

时间:2017-11-24 16:25:53

标签: 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']);

4 个答案:

答案 0 :(得分:2)

是的,可以在Angular 4&amp; 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();
            }
        );

    });
}

答案 1 :(得分:1)

分配给location.href类似于:

this.router.navigateByUrl('/signin');

navigate方法采用路由器命令而非路径。

答案 2 :(得分:1)

您可以使用rxjs的catch运算符来执行此操作:

index.xml

答案 3 :(得分:0)

对我来说,router.navigate 也不起作用。问题是我使用的是 ngx 智能模式;因此,当弹出窗口打开时,router.navigate 无法正常工作,但可以使用 windows.navigate。