0
我有一個相當大的AngularJS(又名Angular 1)應用程序,它是用Typescript編寫的。我已經決定新功能應該用Angular(又名Angular 4)編寫,並已採取步驟在「混合模式」下推廣應用程序。在混合助推應用程序中的角度DI
這似乎工作(所有的AngularJS工作正常),我已經添加了一個單一的Angular組件,並呈現罰款。
當我嘗試向Angular添加一個Angular服務(所有Angular 4到目前爲止)時,問題就出現了。角度無法工作,吐出似乎無處不在 無法解決...錯誤的所有參數。但是,如果我用@Inject在組件構造函數中標記類型,那麼它工作正常。
所有文檔指出,我不應該需要常規使用@Inject,那麼爲什麼這會失敗呢?
我的中期需要將AngularJS服務注入到Angular組件和服務中,而這種情況並沒有讓我充滿信心。
app.module.ts:
// All AngualarJS definitions appear before this section.
@NgModule({
imports: [
BrowserModule,
UpgradeModule,
],
declarations: [
AppComponent,
OrgSummaryComponent
],
providers: [
OrgDetailsService,
],
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: true});
});
ORG-details.service.ts:
import {Injectable} from "@angular/core";
export class OrgDetails {
public orgName: string;
}
@Injectable()
export class OrgDetailsService {
getOrgDetails() : OrgDetails {
const od = new OrgDetails();
od.orgName = "Some Org Name from a REST service";
return od;
}
}
ORG-summary.component.ts:
import {Component, Inject, OnInit} from "@angular/core";
import {OrgDetailsService} from "./org-details.service";
@Component ({
selector: "orgsummary",
template: "<h2>{{OrgName}}</h2>",
})
export class OrgSummaryComponent implements OnInit {
constructor (
/*@Inject(OrgDetailsService)*/ private orgs: OrgDetailsService, // Only works if I uncomment the @Inject
) {
}
public OrgName: string;
ngOnInit(): void {
this.OrgName = `${this.orgs.getOrgDetails().orgName}`;
}
}
tsconfig.json :
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"sourceMap": true,
"noImplicitAny": true,
"declaration": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules",
"**/*.spec.ts"
],
"include" : [
"app/**/*.ts"
]
}
非常感謝, 傑夫
你可以分享你tsconfig? – yurzui
當然:) { 「compilerOptions」:{ 「模塊」: 「CommonJS的」, 「目標」: 「ES6」, 「sourceMap」:真實, 「noImplicitAny」:真實, 「宣言」:真, 「experimentalDecorators」:真 }, 「排除」:[ 「node_modules」, 「**/* spec.ts」 ], 「包括」:[ 「應用程序/ **/* .ts「 ] } – jeffeld
http://stackoverflow.com/questions/39602890/angularjs-2-0-cant-inject-anything-through-componen t-constructor/39608530#39608530 – yurzui