gpt4 book ai didi

拦截器错误中的 Angular 2 重定向

转载 作者:行者123 更新时间:2023-12-05 07:35:12 24 4
gpt4 key购买 nike

我写了这个拦截方法:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
console.log('EVENT:', event);
}, (err: HttpErrorResponse) => {
const message = err.error.message;
if (message == 'You need to activate your account!') {
// TODO: Redirect to '/auth/not-activated'
}
});
}

如果我从服务器收到特定的错误消息,我需要将用户重定向到地址/auth/not activated

我怎样才能做到这一点?

我已经试过了

this.router.navigateByUrl(url);

但这行不通。

最佳答案

这和我之前在回答中提到的一样

像下面这样注册拦截器

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { UnauthorizedInterceptor } from './../auth/UnauthorizedInterceptor';
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorizedInterceptor,
multi: true
}
]
})
export class AppModule {}

阅读:UNAUTHORIZED INTERCEPTER FOR ANGULAR

import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';

@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(
private router: Router
) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((err: any) => {
if (err instanceof HttpErrorResponse && err.status === 401) {
this.router.navigate(['/login'], {
queryParams: {
redirectTo: document.location.pathname
}
});

// this response is handled
// stop the chain of handlers by returning empty
return Observable.empty();
}

// rethrow so other error handlers may pick this up
return Observable.throw(err);
});
}

试试这个,在 observable 上使用 catch 方法,并使用 navigate 方法进行导航

return next.handle(req).catch(
(err: HttpErrorResponse) => {
this.router.navigate(['/auth/not-activated']);
return Observable.throw(err);
});

关于拦截器错误中的 Angular 2 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678521/

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