Ste*_*tef 5 subscription eventemitter typescript sharedservices angular
我在我的主要组件中发出了一个事件:
main.component.ts
this.sharedService.cartData.emit(this.data);
Run Code Online (Sandbox Code Playgroud)
这是我的sharedService.ts
import { Component, Injectable, EventEmitter } from '@angular/core';
export class SharedService {
cartData = new EventEmitter<any>();
}
Run Code Online (Sandbox Code Playgroud)
在我的其他(Sub)组件中,我想访问此值,但不知何故,订阅不起作用:
dashboard.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));
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?当我将数据作为Injectable传递时,它工作正常.在一些REST调用之后发生事件(在主组件中).
更新
所以问题是在第一次发射事件之后创建了子组件.我想在这种情况下最好直接将数据注入subcompnent.
更新: 不再维护Plunker示例请在此处使用StackBlitz示例 https://stackblitz.com/edit/stackoverflow-questions-45351598-angular?file=src%2Fapp%2Fapp.component.ts
我使用您在上面提供的代码创建了一个有效的plunker示例.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 {}
Run Code Online (Sandbox Code Playgroud)
查看生命周期钩子https://angular.io/guide/lifecycle-hooks
| 归档时间: |
|
| 查看次数: |
35845 次 |
| 最近记录: |