gpt4 book ai didi

angular - 将数据(从后端)解析为根组件

转载 作者:行者123 更新时间:2023-12-05 08:12:58 25 4
gpt4 key购买 nike

我已经为这个问题苦苦挣扎了一段时间:

我正在尝试将来自后端的数据(从本地存储重新验证用户 token )解析到根组件中,以便我可以相应地设置 HTTP header 。

解析为“普通”组件工作得很好,我只是在与根组件作斗争。

主要.ts

platformBrowserDynamic().bootstrapModule(AppModule);

应用程序路由.ts

export const AppRoutes: Routes = [{
path: '',
resolve: {
token: LoginService
},
children: [
...HomeRoutes,
...LoginRoutes,
...DashboardRoutes
]
}];

应用程序模块.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
]
})

应用程序组件.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']);
}
}

非常感谢您的任何建议!!!

问候罗宾

最佳答案

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

关于angular - 将数据(从后端)解析为根组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41944686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com