将Angular 1服务注入Angular 4

时间:2017-05-09 12:51:07

标签: javascript angularjs angular typescript

使用概述here的过程,我试图将Angular 1服务注入Angular 4应用程序。该应用程序以混合模式进行自举(并且可以运行,因为我运行了一些Angular 4组件和服务)。

每当我尝试注入Angular 1服务时,我都会无法读取未定义的属性'get'

升级-providers.ts:

import {LinksService} from "./+services/links/links";

export function linksServiceFactory(i: any) {
  return i.get('bfLinksService');         // <--- Errors here!
}
export const linksServiceProvider = {
  provide: LinksService,
  useFactory: linksServiceFactory,
  deps: ['$injector']
};

尝试使用LinksService的我的Angular 4服务看起来像:

@Injectable()
export class EntityService {

    constructor (
        private http: Http,
        private links: LinksService
    ) {

    }

    get(id: string): Observable<OrgDetails> {
        // Do something
    }
}

最后,LinksService(Angular 1服务,用Typescript编写)看起来像:

export class LinksService {

    static $inject = ["$log", "$location", PROPERTIES_SERVICE];

    private contentHost : string;
    private thisAppHost : string;

    constructor (private $log : ng.ILogService, private $location : ng.ILocationService, private props : IPropertiesService) {
        this.init();
    }

    // Service functions elided
}

引导程序和模块内容:

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        UpgradeModule,
    ],
    declarations: [
        AppComponent,
        OrgSummaryComponent,
    ],
    providers: [
        EntityService,
        linksServiceProvider
    ],
    bootstrap: [
        AppComponent,
    ],
})
export class AppModule {
    ngDoBootstrap() {
        // Does nothing by design.
        // This is to facilitate "hybrid bootstrapping"
    }
}

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
    const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
    upgrade.bootstrap(document.body, [AppModuleName], {strictDi: false});
});

Angular 1(遗留)的东西都运行良好。

似乎Angular无法找到$ injector,但是不应该在那里吗?

非常感谢任何建议, 杰夫

2 个答案:

答案 0 :(得分:3)

我生命中的两天我不会回来但是......

刚刚发现:

https://github.com/angular/angular.io/issues/3317

基本上文档是错误的。通过向app模块添加一个constrigator来调用upgrade.bootstrap,一切正常。

export class AppModule {

    constructor(upgrade: UpgradeModule) {
        upgrade.bootstrap(document.body, [AppModuleName], {strictDi: true});
    }

    // Does nothing by design.
    // This is to facilitate "hybrid bootstrapping"
    ngDoBootstrap() {}
}

platformBrowserDynamic().bootstrapModule(AppModule);

感谢那些回复的人。

答案 1 :(得分:0)

实际上,实例化AngularJS的更好方法是:

platformBrowserDynamic().bootstrapModule(AppModule)
  .then(platformRef => {
    const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
    upgrade.bootstrap(document.body, ['app'], { strictDi: false });
  })
  .catch(err => console.log(err));