所以我正在使用Angular 2 final(2.0.0),让我说我创建了一个WidgetsModule,其中包含一些指令和组件,可以帮助我构建我的应用程序,然后将其导入我的AppModule中
import { NgModule } from '@angular/core';
import { UniversalModule } from 'angular2-universal';
import { WidgetsModule } from '../../../widgets';
import { App, appRouting } from './';
@NgModule({
imports: [
UniversalModule,
WidgetsModule,
appRouting
],
providers: [ AppPresenter ],
declarations: [ App ],
exports: [ ],
bootstrap: [ App ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
然后我想在子模块中使用小部件,如HomeModule,CartModule等.如何在不必在每个其他模块中导入WidgetsModule的情况下使小部件可用?
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { WidgetsModule } …Run Code Online (Sandbox Code Playgroud) 因此,我使用如下基本拦截器创建了一个angular2模块来处理HTTP拦截:
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authService = this.injector.get(AuthService);
if(authService.isAuthenticated()){
const authReq = request.clone({
setHeaders: {
Authorization: `Bearer ${authService.getAccessToken()}`
}
});
let handle = next.handle(authReq).do(event => {
if(event instanceof HttpResponse){
if(event.headers.has('Authorization')){
authService.updateToken(event.headers.get('Authorization').split(' ')[1]);
}
}
});
return handle;
}else{
return next.handle(request);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当从服务器发送一个新的授权标头时,它将为http请求添加一个授权标头,并更新其自己的标头。它的导入和正常提供如下:
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
},
Run Code Online (Sandbox Code Playgroud)
因此,将auth angular2模块编译并导入到我的app.module.t中,效果很好。直到我尝试从子模块中使用它。此处的最高答案:Angular2中从父模块到子模块的继承导入声称angular2不会让您全局使用整个应用程序。它是否正确?
通过导入RequestInterceptor并在模块的提供程序中对其进行设置,我可以从子模块中获得该功能,但是我不想这样做,以使其使用起来不那么麻烦。