我的应用程序子组件需要出于各种原因访问AppComponent的活动实例,所以我尝试使用下面的方法将AppComponent引用到ChildComponents中,它可以工作,但它不是注入AppComponent的活动实例而是获取新的实例我所有子组件中的AppComponent。那么如何解决这个问题。
在GIT中发布消息来源
https://github.com/jeevaengg21/angular2-parent-inject
更新
import { NgModule, Inject, forwardRef } from '@angular/core';
@Component({
selector: 'child-page1',
templateUrl: './child.component.html',
})
export class ChildComponent1 implements IChild {
...
constructor(private appComponent: AppComponent) {
console.log('inside ChildComponent1'+appComponent);
}
...
}
child.lazy.module.ts
import { NgModule, forwardRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildComponent } from './child.component';
import { ChildRoutingModule } from './child.lazy.routing';
import { AppComponent } from '../app.component';
import { AppModule } from '../app.module';
import { Routes, RouterModule } from '@angular/router';
@NgModule({
imports: [CommonModule,ChildRoutingModule],
declarations: [ChildComponent]
})
export class ChildModule {}
child.lazy.routing.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ChildComponent } from './child.component';
const appRoutes: Routes = [
{ path: '', component: ChildComponent },
];
@NgModule({
imports: [
RouterModule.forChild(appRoutes)
],
exports: [
RouterModule
]
})
export class ChildRoutingModule { }
app.routing.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
{ path: '', redirectTo: '/child', pathMatch: 'full' },
{ path: 'child', loadChildren: "app/child/child.lazy.module#ChildModule" },
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, AppRoutingModule,
FormsModule,
HttpModule,
ReactiveFormsModule,
],
providers: [MainService],
bootstrap: [AppComponent]
})
export class AppModule {}
解决:
升级Angular2和Angular-cli