Angular2 在应用程序启动之前初始化用户 [英] Angular2 initialize user before app starts
问题描述
我的应用程序在 localstorage 中有 api_token
,我想在应用程序启动之前从我的 REST 中确定使用 api_token
的用户.我怎样才能做到这一点?我使用过 routeResolvers,但我想在应用启动前确定用户,而不是在路由启动时确定用户.
My app has api_token
in localstorage, and I want to determine a user using api_token
from my REST before app starts. How can I do that? I've used routeResolvers, but I want to determine a user before app starts instead determine a user when route starts.
推荐答案
如果您只需要在引导 Angular 之前运行一些代码,那么您可以……在 Angular 之外运行一些代码并让该代码引导应用程序.
If you just need to run some code before bootstrapping Angular, then you can just... run some code outside of Angular and have that code bootstrap the app.
例如:
// main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
// Here, some code retrieving api_token from localStorage.
// Only call the line below once your code is done.
// You might have to place that line in a callback of some sort.
platformBrowserDynamic().bootstrapModule(AppModule);
但我怀疑您想运行代码并将检索到的值传递给 Angular.在这种情况下,请查看 APP_INITIALIZER
.请参阅说明+代码示例.
But I suspect you want to run code AND pass the retrieved value to Angular. In that case, take a look at APP_INITIALIZER
. See explanation + code sample.
这篇关于Angular2 在应用程序启动之前初始化用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!