HttpInterceptor内部的路线导航

man*_*uel 6 interceptor angular 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']);
                 }
             }
         });
?}
Run Code Online (Sandbox Code Playgroud)

但是什么也没发生。

我只有在使用的情况下才能重定向到登录页面

window.location.href = '/signin';
Run Code Online (Sandbox Code Playgroud)

代替

this.router.navigate(['/signin']);
Run Code Online (Sandbox Code Playgroud)

Was*_*tna 5

是的,这是可能的,在 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);
                }
            });

    }

}
Run Code Online (Sandbox Code Playgroud)

以下是服务代码,请确保在错误情况下使用 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();
            }
        );

    });
}
Run Code Online (Sandbox Code Playgroud)


And*_*ang 1

分配给location.href类似于:

this.router.navigateByUrl('/signin');
Run Code Online (Sandbox Code Playgroud)

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