Angular2 passing data between NON parent - child components

时间:2017-04-09 23:14:19

标签: angular

So I have two components - in terms of where they are in the component hierarchy, one is like a 3rd removed grandparent of the other component - and I'm looking to pass data between them. I thought the way to do this would be to write a service as such:

@Injectable()
export class DataService {
  dataChange: EventEmitter<any> = new EventEmitter<any>();

  constructor() {}
  change(data){
          this.dataChange.next(data)
      }
  }
}

Then subscribe to it on both components, and call the change function when they are looking to pass data. It seems though, that Angular2 doesn't like this, and just ignores whatever comes through the subscription. I've console logged the subscription and they are 'subscribed' and opened.

I can monkey patch around this by calling the component itself and using jQuery or vanilla Javascript to manipulate the DOM, but I can't set values on the component itself, because Angular2 doesn't like it when people do that either, and will just remove all subscriptions.

How does one actually pass data between two distant components in an Angular2 way?

EDIT: opened issue here: https://github.com/angular/angular/issues/15856

2 个答案:

答案 0 :(得分:1)

You are on the right track with using a service at least. The angular Docs have a nice write up doing just this, which can be found here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

The title of the doc implies a parent-child relationship, but as long as the service is injected into both components, it should work the same way.

答案 1 :(得分:0)

See Github issue for a better response:

So what I did was wrong I put the service as a provider in both the components, but what I needed to do was put the service as a provider at the top of the component hierarchy - in my instance app.component.ts.

Then just import the service into the two components (without making them providers).