passing data between siblings Angular2 using obser

2019-07-28 10:38发布

I am trying to pass data between two components say, B and C which are at the same level and are being used by one component say, A.

Now in template of A I am using B and C like this:

<div><b></b></div>
<div><c></c></div>

B is a dropdown component and the C component wants to use the selected dropdown value.

I have created a service to get the dropdown value like this:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class PassValueService {


private valueSource = new Subject<Array<string>>();

value$ = this.valueSource.asObservable();

passValue(data: Array<string>) {
 console.log('inside pass value service', data);
 this.valueSource.next(data);
 this.valueToBePassed = data;
}

}

Now in C component I am trying to subscribe to the event like this:

 constructor(private passValueService: PassValueService)

 this.subscription = this.passValueService.value$.subscribe(data=> {
  console.log('constructor', data);
});

I tried doing it in constructor, ngOnInit, ngDoCheck but with no help.

Can any body help me understand why I am not getting the value from the Observable? Let me know if there is another approach that can be used.

1条回答
SAY GOODBYE
2楼-- · 2019-07-28 11:06

A simpler way for siblings is to use template variables and binding

<div><b #b></b></div>
<div><c [selected]="b.selected"></c></div>

where C has an input

@Input() selected:string; // or any other type

For your service, ensure it is provided only once. For example in the parent component. If the service is provided at B or C, then it can't be shared between siblings.

If you provide it in @NgModule() then your whole application shares the same instance. This will only work if B and C are only used once at the same time in your entire application.

查看更多
登录 后发表回答