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

mbskvtky  于 2023-01-06  发布在  TypeScript
关注(0)|答案(1)|浏览(122)

我已经编写了这个拦截方法:

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);

但这没用。

vngu2lb8

vngu2lb81#

我在刚才的答复中亦有这样的建议
注册拦截器如下

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);
        });
    }

试试看,在观测上用catch方法,在航路上用navigate方法导航

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

相关问题