如何在Angular 5组件中注入AngularJS服务?

时间:2018-05-17 13:57:09

标签: angularjs angular angular-upgrade

我正在使用ngUpgrade将AngularJS项目迁移到Angular 5,但是当我尝试在我的一个新组件中注入AngularJS服务时遇到了问题。

我关注Angular's upgrade guide并创建了一个使用$injector的serviceProvider(请参阅下面的代码),但我一直收到此错误:

  

core.js:1449 ERROR错误:未捕获(在承诺中):错误:尝试在设置之前获取AngularJS注入器。

我怀疑我需要在某处使用forwardRef来解决这个问题,但我无法找出方法和地点(以及原因)。

按照升级指南的示例,我创建了一个serviceProvider,如下所示:

AJS升级-providers.ts:

// The AngularJS service I want to use
import { AuthenticationService } from '../ajs/services/authentication.service';

export function authenticationServiceFactory($injector) {
    return $injector.get('authentication');
}

export const authenticationServiceProvider = {
    provide: AuthenticationService,
    useFactory: authenticationServiceFactory,
    deps: ['$injector']
};

然后我将它提供给应用程序的NgModule:

app.module.ts:

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        UpgradeModule,
    ],
    providers: [
        authenticationServiceProvider,
    ],
    bootstrap: [
        AppComponent,
    ],
})
export class AppModule {
}

我使用ngUpgrade引导该模块:

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { UpgradeModule } from '@angular/upgrade/static';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

// Import our AngularJS module
import '../ajs/app';

platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .then(platformRef => {
        // Use the upgrade module to bootstrap the hybrid
        const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
        upgrade.bootstrap(document.documentElement, ['myAngularJSApp']);
    });

如果我理解正确,这应该允许我直接将AngularJS服务注入到我的组件中,如下所示:

login.component.ts

import { Component } from '@angular/core';

import { AuthenticationService } from '../ajs/services/authentication.service';

@Component({
    selector: 'my-login-page',
    templateUrl: './login-page.component.html'
})
export class LoginPageComponent {    
    constructor(private authenticationService: AuthenticationService) {
        console.log('authentication', authenticationService);
    }
}

我可以做些什么来进一步简化这个吗?我试图尽可能地遵循升级指南,为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

您需要添加

providers: [AuthenticationService] 

在组件声明中,如下所示:

import { Component } from '@angular/core';

import { AuthenticationService } from '../ajs/services/authentication.service';
@Component({
    selector: 'my-login-page',
    templateUrl: './login-page.component.html',
    providers: [AuthenticationService] 
})
export class LoginPageComponent {    
    constructor(private authenticationService: AuthenticationService) {
        console.log('authentication', authenticationService);
    }
}