我正在创建一个外部库,其主要目的是为我的所有Web应用程序实现唯一的拦截器。
基本上,我创建了一个Angular库,并在Web应用程序中实现了该库,并且可以运行,但是当我需要通过Angular路由器重定向到其他内部路由时,这是不可能的。
我的问题是:还有其他方法吗?还是可以创建一个自定义路由器,然后将路由传递到外部库,以设置到该自定义路由器的路由? 将路由器依赖项注入外部lib拦截器怎么办?那可能吗?
我的代码:
App.module
//Routing
import { AppRoutingModule } from './app-routing.module';
//Libs
import { AuthInterceptor } from 'auth-lib';
import { HeaderComponent } from './shared/layout/header/header.component';
@NgModule({
declarations: [
AppComponent,ForbiddenComponent,MenuComponent,BasicComponent,HeaderComponent
],imports: [
BrowserModule,HttpClientModule,AppRoutingModule
],providers: [
ProfileService,{ provide: HTTP_INTERCEPTORS,useclass: AuthInterceptor,multi: true },{ provide: APP_BASE_HREF,useValue: '/' }
],bootstrap: [AppComponent]
})
export class AppModule { }
外部拦截器库
@Injectable({
providedIn: 'root'
})
export class AuthInterceptor implements HttpInterceptor {
constructor (private router: Router) {}
intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(catchError(error => {
this.handleAuthError(error);
return of(error);
}) as any);
}
private handleAuthError(error: HttpErrorResponse): Observable<any> {
if (error.status === FORBIDDEN) {
console.log('SESSION STATUS: FORDIBBEN');
//window.location.href = ERR_AUTH_URL; //Redirect works,but this refresh the web app
this.router.navigate([ERR_AUTH_URL]);
}
throw error;
}
}