2017-07-27 84 views
2

我在我的主发光成分的事件订阅的事件:角4发射和在共享服务

main.component.ts

this.sharedService.cartData.emit(this.data); 

这是我的sharedService.ts

import { Component, Injectable, EventEmitter } from '@angular/core'; 
export class SharedService { 
    cartData = new EventEmitter<any>(); 
} 

在我的其他(子)组件,我想访问这个值,但不知何故,认购不工作:

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)); 
} 

我错过了什么吗?当我将数据作为Injectable传递时,它工作正常。 发送事件(在主要组件中)发生在一些REST调用之后。

**************更新***************** 所以问题是子组件是在第一个发射之后创建的的事件。我想在这种情况下,最好直接将数据注入子组件。

+1

你在哪里提供sharedService?服务实例可能不相同,如果您在不同模块中提供服务,则会发生这种情况。 –

+0

我在父app.module.ts提供程序中声明了它:[SharedService ...], – Stef

+0

以及这两个组件如何同时加载?在不同的路线? –

回答

3

我使用上面提供的代码创建了一个工作的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 {} 

这里查看生命周期挂钩https://angular.io/guide/lifecycle-hooks

+0

这工作正常,因为它的工作与点击监听。我试图找出当我在代码中发出事件时必须使用哪个函数。 – Stef

+0

它也适用于ngAfterViewInit,它是角度生命周期钩子的一部分。检查出https://angular.io/guide/lifecycle-hooks –

+0

我将我的版本更改为ngAfterViewInit,它在我点击某处时起作用。当应用程序最初加载时,子组件会在第一个事件触发后加载,因为我在main.component.html中声明了它。1)发光事件 2)仪表板构造函数 3)仪表板AfterViewInit – Stef