我在我的主要组件中发出一个事件:
主要组件.ts
this.sharedService.cartData.emit(this.data);
这是我的sharedService.ts
import { Component, Injectable, EventEmitter } from '@angular/core';
export class SharedService {
cartData = new EventEmitter<any>();
}
在我的其他(子)组件中,我想访问该值,但不知何故,订阅不起作用:
仪表板.ts
private myData: any;
constructor(private sharedService: SharedService) {
this.sharedService.cartData.subscribe(
(data: any) => myData = data,
error => this.errorGettingData = <any>error,
() => this.aggregateData(this.myData));
}
我错过了什么吗?当我将数据作为可注入对象传递时,它工作得很好。
在一些 REST 调用之后会发出事件(在主组件中)。
Update
所以问题是子组件是在事件第一次发出后创建的。我想在这种情况下最好将数据注入subcompnent
直接地。
Update:Plunker 示例不再维护,请使用 StackBlitz
例子在这里https://stackblitz.com/edit/stackoverflow-questions-45351598-angular?file=src%2Fapp%2Fapp.component.ts https://stackblitz.com/edit/stackoverflow-questions-45351598-angular?file=src%2Fapp%2Fapp.component.ts
我使用您上面提供的代码创建了一个工作的 plunker 示例。https://plnkr.co/edit/LS1uqB?p=preview https://plnkr.co/edit/LS1uqB?p=preview
import { Component, NgModule, Injectable, EventEmitter, AfterViewInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@Injectable()
export class SharedService {
cartData = new EventEmitter<any>();
}
@Component({
selector: 'app-app',
template: `
<h1>
Main Component <button (click)="onEvent()">onEvent</button>
</h1>
<p>
<app-dashboard></app-dashboard>
</p>
`,
})
export class App implements AfterViewInit {
data: any = "Shared Data";
constructor(private sharedService: SharedService) {
}
ngAfterViewInit() {
this.sharedService.cartData.emit("ngAfterViewInit: " + this.data);
}
onEvent() {
this.sharedService.cartData.emit("onEvent: " + this.data);
}
}
@Component({
selector: 'app-dashboard',
template: `
<h2>
Dashboard component
</h2>
<p>
{{myData}}
</p>
`,
})
export class AppDashboard implements AfterViewInit {
myData: any;
constructor(private sharedService: SharedService) {
this.sharedService.cartData.subscribe(
(data: any) => {
console.log(data);
this.myData = data;
});
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, AppDashboard ],
providers: [ SharedService ],
bootstrap: [ App ]
})
export class AppModule {}
在此处查看生命周期挂钩https://angular.io/guide/lifecycle-hooks https://angular.io/guide/lifecycle-hooks
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)