我一直在努力解决这个问题很长一段时间了:
我正在尝试从后端解析数据(从本地存储重新验证用户令牌)到根组件中,这样我就可以相应地设置HTTP头。
决心进入"正常"组件工作正常,我只是在与根组件挣扎。
main.ts
platformBrowserDynamic().bootstrapModule(AppModule);
app.routes.ts
export const AppRoutes: Routes = [{
path: '',
resolve: {
token: LoginService
},
children: [
...HomeRoutes,
...LoginRoutes,
...DashboardRoutes
]
}];
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(AppRoutes),
MaterialModule.forRoot(),
FlexLayoutModule.forRoot(),
LoginModule,
HomeModule,
DashboardModule
],
providers: [
SessionService,
LocalstorageService,
HttpClient,
LoginService
],
bootstrap: [
AppComponent
]
})
app.component.ts
@Component({
selector: 'nos-app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.scss']
})
export class AppComponent implements OnInit {
constructor(private _route: ActivatedRoute) {
// this is undefined
console.log(this._route.snapshot.data['token']);
}
}
dashboard.component.ts
@Component({
selector: 'nos-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.scss']
})
export class DashboardComponent implements OnInit {
constructor(private _route: ActivatedRoute) {
// this is fine
console.log(this._route.snapshot.data['token']);
}
}
非常感谢任何建议!!!
此致 罗宾
答案 0 :(得分:-3)
export class AppComponent implements OnInit {
constructor(private _route: ActivatedRoute) {
this._route.data.subscribe(data => {
console.log(data['token']);
})
}
}
另见https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard