首页 > 解决方案 > 试图理解 ngOnInit 和 promise

问题描述

嗨,我是 Angular 和 javascript 承诺的新手...我正在尝试执行以下代码,但我有几个问题...

代码在这里。我可以看到一个充满模拟数据的表格

 response;
 promise_response;
 data;

 ngOnInit() {
    this.response = this.bitbucket.commits.list({
      include: 'master',
      repo_slug: 'test',
      workspace: 'test',
    });

    this.promise_response = Promise.resolve(this.response);

    this.promise_response.then((data) => {
      this.data = data.data.values;
      console.log(data.data.values);
      console.log('data');
    });

    console.log('test');

    // replace below with actual data;
    for (let i = 0; i < 5; i++) {
      const item = {
        id: '1',
        comment: faker.random.words(),
        time: faker.date.future(),
      };
      this.dataSource.push(item);
    }
  }
}
  1. 我正在做这个“this.promise_response = Promise.resolve(this.response);” 因为我注意到当我控制台.log(this.response)时,我得到了“zoneAwarePromise”......这导致谷歌关于承诺并让我相信我需要以某种方式解决它......

  2. 我添加了一些代码来解决承诺(不确定它是否正确),我注意到首先打印“测试”..然后是“数据”..我想知道为什么......

  3. 我在 this.promise_response.then 中移动了以下内容,但是我的表是空的......为什么......

// replace below with actual data;
    for (let i = 0; i < 5; i++) {
      const item = {
        id: '1',
        comment: faker.random.words(),
        time: faker.date.future(),
      };
      this.dataSource.push(item);
    }

谢谢!


更新:

现在以下工作按预期工作。谢谢你。

ngOnInit() {
    this.bitbucket.commits
      .list({
        include: 'test',
        repo_slug: 'test',
        workspace: 'test',
      })
      .then((response) => {
        this.data = response.data.values;
        this.dataSource = this.data;
      });
  }

标签: javascriptangularpromise

解决方案


推荐阅读