我写过这个拦截方法:
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'
}
});
}
如果我收到服务器特定的错误消息,我需要将用户重定向到地址/身份验证/未激活
我怎样才能实现这一目标?
我已经尝试了
this.router.navigateByUrl(url);
但这不起作用。
答案 0 :(得分:0)
我在之前的回答中建议
注册拦截器如下所示
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);
});