html - 您将如何将带有参数的可观察对象作为@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 作为输入传递
希望能很好地解释我的问题。提前致谢。
解决方案
如果你想传递一个 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 上取消订阅它。
推荐阅读
- python - 如何在 Django 表单中使用自定义值填充/填充 ChoiceField
- node.js - 如果第一个服务端点根据状态码忙,则回退到另一个服务端点
- firebase - Firebase 客户端错误:自定义令牌对应于不同的受众
- django - Recombee 批处理不发送所有数据
- php - NGINX 默认站点工作,但另一个端口上的一个不工作
- java - 如何正确访问 ArrayList 以在 HashMap Java 中进行迭代?
- tensorflow.js - 如何定义具有数千个可能分类值的输入张量?
- java - 套接字连接程序(TCP/IP)适用于 localhost/common 网络但不适用于其他 IP
- android - 如何使用过时的 android sdk 版本
- python - pygame.draw.rect 无法处理元组中的值和整数之间的操作,但任何其他函数都可以