Elkin
Elkin

Reputation: 900

How would you pass an observable with params as @Input?

The goal is to pass an http request from component 1 to component 2 and set its params on component 2.

This is my approach pseudo code:

Component 1 HTML

<app-component-2 [obs]="obs"></app-component-1>  

Component 1 TS

export class Component1 {

   obs : Observable<any>;      

   constructor(private service : SomeService){
     this.obs = this.service.method(param1 ,param2 ,param3);  //Passing param1, param2 and param3 as Inputs on Component2 is not an option 
  }
} 

Component 2 TS

export class Component2{
  Input() obs : Observable<any>;
}  

Obs: Passing param1, param2 and param3 as Inputs is not an option

Hope to have explained my question well. Thanks in advance.

Upvotes: 0

Views: 387

Answers (1)

Soukyone
Soukyone

Reputation: 577

If you want to pass an observable, you can do it like a normal object:

Component 1:

export class Component1 {

 obs : Observable<any>;      

 constructor(private service : SomeService){
  this.obs = this.service.method(param1 ,param2 ,param3);
 }
} 

Component 2:

export class Component2 implements OnInit {

@Input() obsFromParent: Observable<any>;

ngOnInit() {
  this.obsFromParent.subscribe((data) => {// do what you want });
 }
}

If the observable you pass, is a no-finite observable, think to unsubscribe it, on the ngOnDestroy from Component2.

Upvotes: 1

Related Questions