首页 > 解决方案 > 您将如何将带有参数的可观察对象作为@Input 传递?

问题描述

目标是将 http 请求从组件 1 传递到组件 2,并将其参数设置在组件 2 上。

这是我的方法伪代码:

组件 1 HTML

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

组件 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 
  }
} 

组件 2 TS

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

Obs:不能选择将 param1、param2 和 param3 作为输入传递

希望能很好地解释我的问题。提前致谢。

标签: htmlangulartypescriptparametersobservable

解决方案


如果你想传递一个 observable,你可以像普通对象一样做:

组件 1:

export class Component1 {

 obs : Observable<any>;      

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

组件 2:

export class Component2 implements OnInit {

@Input() obsFromParent: Observable<any>;

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

如果您传递的 observable 是无限的 observable,请考虑在 Component2 的 ngOnDestroy 上取消订阅它。


推荐阅读