【问题标题】:Angular2 initialize user before app startsAngular2在应用程序启动之前初始化用户
【发布时间】:2017-01-21 22:15:27
【问题描述】:

我的应用在本地存储中有 api_token,我想在应用启动之前从我的 REST 中确定使用 api_token 的用户。我怎样才能做到这一点?我使用了routeResolvers,但我想在应用启动之前确定用户,而不是在路由启动时确定用户。

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果您只需要在引导 Angular 之前运行一些代码,那么您可以...在 Angular 之外运行一些代码并让该代码引导应用程序。

    例如:

    // 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。见explanation + code sample

    【讨论】:

    • 感谢您的帖子。 APP_INITIALIZER 的替代方法是使用 localStorage 将数据传递到 Angular。
    【解决方案2】:

    我最近在 How to call an rest api while bootstrapping angular 2 app 上用示例代码回答了这个问题。

    这正是您要寻找的。​​p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2016-12-13
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多