angular6 httpclient已经为字段赋值了,为什么字段一直undefined?

图片描述

已经执行到黄色部分了,res['data'].itemMaterialType=3,
this.itemMaterialType = res['data'].itemMaterialType; 这句话已经执行了,为什么this.itemMaterialType一直是undefined;理论上this.itemMaterialType=3才对啊;

以下是封装的方法,

  async searchData() {
    this.itemMaterialType = '4';
    await this.api.Dispatch.queryProcessDetailByProcessId({
      processId: this.processId
    })
      .then(res => {
        this.data = res['data'];
        this.isFeedMaterial = res['data'].isFeedMaterial.toString();
        this.itemMaterialType = res['data'].itemMaterialType;
      });
  }
    queryProcessDetailByProcessId: async (option) => await this.http.getByPromise('/api/ScheduleProcess/GetProcessDetail', option),
  async getByPromise(url: string, params: {}) {
    return await this.http.get(this.domain + url, { observe: 'body', params: params })
      .toPromise();
  }
阅读 3.6k
5 个回答

1 .then 发生在获取数据之后, 无需使用async await

2 获取res 后 取值 可以直接 使用简写使用点语法 res.data

3 api 中 已经转换成 promise 后 resolve(数据) reject(cache Error) 无需强制转成 同步

this上下文变了。你可以把this打印出来看看,指向哪里了。

既然用了sync await ,为什么 又带then,

浏览器假象,控制台打印的不一定就是真实的。有的时候this会出现bug,但是在代码中用不会有问题。如果代码中使用的时候出现了问题可以再找原因

VS code调试状态this一直是undefined,但是运行都是正常的数据也可以显示;用浏览器调试发现this也是正常的;巨坑

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题