使用此处概述的过程,我尝试将 Angular 1 服务注入到 Angular 4 应用程序中。该应用程序在混合模式下引导(并且工作,因为我正在运行一些 Angular 4 组件和服务(。
每当我尝试注入 Angular 1 服务时,我都会得到无法读取未定义的属性"get"。
upgraded-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']
};
我的 Angular 4 服务正在尝试使用 LinksService,如下所示:
@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,但无论如何不应该在那里吗?
非常感谢您的任何建议,杰夫
我生命中的两天我不会回来,但是...
刚刚发现这个:
https://github.com/angular/angular.io/issues/3317
基本上文档是错误的。通过在应用程序模块中添加一个构造器,并在其中调用 upgrade.bootstrap,一切正常。
导出类应用模块 { 构造函数(升级:升级模块( { upgrade.bootstrap(document.body, [AppModuleName], {strictDi: true}(; } 设计上什么都不做。 这是为了促进"混合引导" ngDoBootstrap(( {}}platformBrowserDynamic((.bootstrapModule(AppModule(;
感谢那些回应的人。
实际上,实例化 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));