Home > Net >  Get data from emitted value
Get data from emitted value

Time:11-04

I am trying to get the values of the data parameter from an emmitted value in my second component

Here is my code

Component 1 TS

this.myService.emitChange({emitValue: 'openFunctionInSidePanel',  data: data });

Component 2 Service file

private emitChangeSource = new Subject<any>();
changeEmitted$ = this.emitChangeSource.asObservable();

emitChange(event) {
  this.emitChangeSource.next(event);
}

Component 2 TS

console.log(this.myService.emitChange);

So how would I get the actual data value in my component 2.ts file?

I currently see

ƒ (event) {
        this.emitChangeSource.next(event);
}

CodePudding user response:

You need "subscribe" to changeEmitted$.

You can do in ngOnInit

//don't forget unsubscribe!!!
ngOnInit()
{
    this.myService.changeEmitted$.subscribe((res:any)=>{
         console.log(res)
    })
}

Or if only want to show the result you can use pipe async

You can declare as public the service in constructor

constructor(public myService:MyService){}

//in html
<div *ngIf="myService.changeEmitted$|async as value">
  {{value.emitValue}} - {{value.data|json}}
</div>

Or declare as private and use an auxiliar variable

changeService$=this.myService.changeEmitted$

constructor(private myService:MyService){}

//in html
<div *ngIf="changeService$|async as value">
   {{value.emitValue}} - {{value.data|json}}
</div>

NOTE: you can also "play" with rxjs operators for,e.g. filter the response and transform to only return the "data"

changeService$=this.myService.changeEmitted$.pipe(
   filter((res:any)=>res.emitValue=='openFunctionInSidePanel'),
   map((res:any)=>res.data)
)

//then subscribe to this.changeService or use in .html `{{changeService|async}}`

NOTE: I add a response because the article indicate in the another answer don't take account the async pipe

CodePudding user response:

Basically, there should be a shared service between the 2 components. Emit the value from component 1 using the service and subscribe to the value from component 2 using the shared service.

Refer to the 4th method of this article which shows how to pass data between unrelated components.

  • Related