【问题标题】:Not able to access data return from service in angular class无法访问角度类服务返回的数据
【发布时间】:2020-10-07 04:36:55
【问题描述】:

无法访问角度组件中服务返回的数据。

  1. 我有以下服务代码。
getData(fromDate: string, toDate: string): Observable<WfAverageTime[]>
  {
   const url ="http://testApi/getData"
   return this.http.get<someObject[]>(url);
 }
  1. 以下组件代码
loadData(fromDate, toDate) {
  let resp = this.testService.getData(fromDate, toDate);
  resp.subscribe((reportData) => {
    this.DataSource.data = reportData as someObject[];
    this.data1 = reportData;
  })

data1 是类级别的变量。我无法在类的任何其他函数中使用此值。正在分配,但在其他方法中仍无法以this.data1 的身份访问。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您需要将逻辑放在您想在订阅内使用该变量的位置,因为它发生 async 所以:

    resp.pipe(
      tap((reportData ) => { ```logic``` })
    ).subscribe((reportData)=> {this.DataSource.data = reportData as someObject[];
        this.data1 = reportData;
        ```logic```
    });
    

    或者,您可以在子组件中使用该值来解决它:

    public reportData = this.testService.getData(fromDate, toDate);
    

    比在 html 中:

    <child-component [model]="reportData"></child-component>
    

    你可以使用 @Input set ... 或 ngOnChanges 来实现逻辑。

    【讨论】:

      【解决方案2】:

      Angular HTTP 客户端的get 方法是一个异步方法,这本质上意味着代码执行不会等到服务调用返回数据。 subscribe 回调中的代码只有在获取数据后才会执行。

      因此,即使data1 是一个类属性,在服务调用完成并且代码执行到达subscribe 回调之前,它仍处于未定义状态。

      为了正确访问值,您必须从 subscribe 回调中执行需要 data1 属性的逻辑。

      loadData(fromDate, toDate) { 
      let resp = this.testService.getData(fromDate, toDate);
      resp.subscribe((reportData) => {
      this.DataSource.data = reportData as someObject[];
      this.data1 = reportData; 
      // data1 becomes available at this point.
      // Call the    methods that use data1 here
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多