gpt4 book ai didi

angular - HttpInterceptor 内部路由导航

转载 作者:太空狗 更新时间:2023-10-29 17:26:58 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com