Angular 2:在引导之前调用服务 [英] Angular 2: Call service before bootstrap

查看:24
本文介绍了Angular 2:在引导之前调用服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在引导我的 Angular 2 (v2.4) 时,我试图运行一个函数,该函数将在应用程序加载之前自动授权用户.但是,这似乎不起作用.

When bootstrapping my Angular 2 (v2.4) I am trying to run a function which will automatically authorise the user before the application loads. However, this does not seem to be working.

import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";
import {enableProdMode, APP_INITIALIZER} from "@angular/core";
import {Http, HttpModule} from "@angular/http";
import {PARAMETERS} from "../config/parameters";
import {AppModule} from "./AppModule";
import {UserRepository} from "../modules/service/repository/UserRepository";
import {SessionManager} from "../modules/service/manager/SessionManager";


export function auth(userRepository: UserRepository) {
    console.log("BOOM!");
    return () => userRepository.autoAuthorize();
};

platformBrowserDynamic().bootstrapModule(AppModule, [
    {
        provide: APP_INITIALIZER,
        useFactory: auth,
        deps: [UserRepository, SessionManager, HttpModule],
        multi: true
    }
])
    .catch(err => console.error(err));

我做错了什么,我怎样才能让它工作?另外,如果我有上面的代码,我是否需要将这些服务添加到 AppModule 中的 providers 数组中?

What am I doing wrong and how can I get it working? Also, if I have this code as above, do I need to add these services to my providers array in the AppModule?

非常感谢

JT

推荐答案

将它依赖的服务添加到您已有的提供者列表中.

Add the services it depends on to the provider list you already have.

...
platformBrowserDynamic().bootstrapModule(AppModule, {
     providers: [ UserRepository, SessionManager, HttpModule,
    {
        provide: APP_INITIALIZER,
        useFactory: auth,
        deps: [UserRepository, SessionManager, HttpModule],
        multi: true
    }
]});
...

https://github.com/angular/angular/blob/4.0.0/packages/core/src/linker/compiler.ts#L90-L109

对于编译器选项,您提供一个带有提供程序的对象.现在应该使用它进行编译,了解您要用于工厂的类.

for compiler options you provide an object that has providers on it. This should now compile with it understanding the classes you want to use for the factory.

请注意,您也可以在 appmodule 的提供程序列表中执行此操作,而不是在引导编译器选项中执行此操作

As a note you could also do this in your appmodule in its provider list instead of doing it on the bootstrap compiler options

这篇关于Angular 2:在引导之前调用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆