【问题标题】:Passing Observable to another component in Angular将 Observable 传递给 Angular 中的另一个组件
【发布时间】:2019-05-30 17:51:55
【问题描述】:

我有两个组件detailsdetails-view

details 中,我必须将 @Input() 的 obserwable 传递给第二个组件。

详细信息组件

 res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }

服务

 getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }

Details-查看 HTML

&lt;dwtalis-view [resources$]="res$"&gt;&lt;/dwtalis-view&gt;

Detalis-Viev TS 组件

@Input()
resouces$: Observable<DetailsResponse[]>

我的问题是如何在 detalis 视图组件中从 resources$ observable 订阅和获取数据。订阅此对象返回错误“resources$ is not a finction can not subscribe”

【问题讨论】:

  • 假设这不是一个错字:this.res$ = service.getData 只是传递函数定义。如果你真的想要一个 observable,你需要执行函数this.res$ = service.getData()。或者,如果您确实打算传递函数定义,那么您对 ​​resource$ 的输入是错误的,它应该是 (id: number, type: string) =&gt; Observable&lt;DetailsResponse[]&gt; 以匹配父组件中的 res$
  • 就像 vlad 说的那样,您传递的是函数而不是可观察的。在您的情况下,您需要调用该 resources$() 函数以从中获取可观察值。资源$().订阅。

标签: angular observable


【解决方案1】:

除了service.getData() 的错字之外,了解何时可以绑定输入属性也很重要。输入没有在构造函数中设置,它们在每次输入更改时都可以在ngOnChanges 生命周期挂钩中使用。或ngOnInit,如果您只想在第一次收到时绑定。

https://angular.io/guide/lifecycle-hooks

【讨论】:

    【解决方案2】:

    键入不匹配。 res$ 是一个函数(id: number, type: string) =&gt; Observable&lt;DetailsResponse[]&gt;,但resouces$ 是一个可观察的Observable&lt;DetailsResponse[]&gt;

    根据您的 cmets,您需要传递一个函数,因为参数在父组件中不可用。所以,你需要接受一个函数为@Input,然后在子组件中执行。

    子组件

    @Input()
    resouces$: (id: number, type: string) => Observable<DetailsResponse[]>;
    
    // Use ngOnInit since @Input properties are populated at this time
    ngOnInit() {
        // Example arguments
        this.resouces$(this.id, this.type).subscribe(results => {
            // Do whatever you need to do with the results
            console.log(results);
        })
    }
    

    【讨论】:

      【解决方案3】:

      您可以像下面的代码一样更改DetailsViewComponent

      export class DetailsViewComponent implements OnInit, OnChanges {
      
        @Input() resouces$: (id: number, type: string) => Observable<DetailsResponse[]>;
      
        constructor(
        ) {}
      
        ngOnInit() {
        }
      
        ngOnChanges(data) {
          if (data.resouces$ && this.resouces$) {
            this.resouces$(this.id, this.type).subscibe(res => {});
          }
        }
      
      }
      

      【讨论】:

      • getData() 的参数在第二个组件中是已知的,因此它不起作用
      • 在创建 DetailsViewComponent 时是否定义了 idtype
      • 是的,,,,,,,,,,,,
      猜你喜欢
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2016-04-07
      • 2021-12-31
      • 1970-01-01
      • 2019-10-23
      相关资源
      最近更新 更多