首页 > 解决方案 > Angular/Typescript - 在返回承诺语句中调用方法

问题描述

我在 Angular 中创建了一个组件,它读取 XML 文件并使用解析器将其显示到组件所具有的 HTML 表中。在解析方法中,我想通过修改读取的 XML 数据中的某些方面来更改显示数据的功能,但是每当我尝试调用将返回更改的数据的方法时,我都会收到错误说明:

“core.js:15724 错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性'CurrencyConvChange' TypeError:无法读取未定义的属性'CurrencyConvChange'”。

这是我的主要组件的打字稿文件的代码:

import { Component, OnInit } from '@angular/core';
import * as xml2js from 'xml2js';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DataStoreService } from '../../data-store.service';

@Component
({
  selector: 'app-tableofshares',
  templateUrl: './tableofshares.component.html',
  styleUrls: ['./tableofshares.component.css']
})

export class TableofsharesComponent
{
  public xmlItems: any;
  new_curr_value;
  test_1 = 1;
  test_2 = 1;

  constructor(private http: HttpClient, private store: DataStoreService)
  // tslint:disable-next-line: one-line
  {
    this.loadXML(); // Runs below function when the project is started.
  }

  async CurrencyConvChange(test_1, test_2)
  {
    console.dir("recieved test 1: " + test_1);
    console.dir("recieved test 2: " + test_2);
    return 0;
  }

  // Loads the data
  loadXML()
  {
    this.http.get('assets/Shares_Data.xml',
    {
      headers: new HttpHeaders()
      .set('Content-Type', 'text/xml')
      .append('Access-Control-Allow-Methods', 'GET')
      .append('Access-Control-Allow-Origin', '*')
      // tslint:disable-next-line: max-line-length
      .append('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method'),
      responseType: 'text'
    }).subscribe((data) => {
      this.parseXML(data).then((data) =>
      {
        this.xmlItems = data; // Assigns xmlItems data from request
      });
    });
  }

  // Manipulates the data
  async parseXML(data)
  {
    return new Promise(resolve =>
    {
      let k: string | number,
      arr = [],
      test_var,
      parser = new xml2js.Parser({trim: true, explicitArray: true});

      parser.parseString(data, function(err, result)
      {
        const obj = result.ShareList;
        // tslint:disable-next-line: forin
        for (k in obj.share)
        {
          const item = obj.share[k];
          const test_1 = item.sharePrice[0].currency[0];
          console.dir("test 1: " + test_1);

          const test_2 = item.sharePrice[0].value[0];
          console.dir("Test 2: " + test_2);

          this.CurrencyConvChange(test_1, test_2);

          arr.push
          ({
            title: item.title[0], companySymbol: item.companySymbol[0],
            numOfShares: item.numOfShares[0], lastShareUpdate: item.lastShareUpdate[0],
            currency: item.sharePrice[0].currency, value: item.sharePrice[0].value
          });
        }
        resolve(arr);
      });
    });
  }
}

我正在“this.CurrencyConvChange(test_1, test_2)”行中调用我想要的方法,并且对收到的错误感到困惑,因为我已经在其他任何方法之前定义了 CurrencyConvChange 方法。我对打字稿有点陌生,想知道这是否是我以前不知道的某种规则?

标签: angulartypescriptangular-promise

解决方案


这与打字稿或承诺无关。这与this参考有关。

你定义一个回调函数

 parser.parseString(data, function(err, result)

在您尝试访问的该功能内this

 this.CurrencyConvChange

但是在那个函数里面是this指你定义的回调函数。不适用于您的组件实例。如果你想指向正确的this使用箭头函数来定义你的回调,如下所示:

 parser.parseString(data, (err, result) => ....

或者使用更丑陋的解决方法,如下所示:

let that = this; // outside of function
// inside your function
that.CurrencyConvChange 

推荐阅读