Angular请求同步async、await使用方式

啥也不说,贴出代码,看执行顺序。


import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  constructor(private client:HttpClient){
    this.initData().then(data => {
      console.log(data);
      console.log('constructor 执行完成')
    });
  }
  async initData(){
    let data = await this.getData();
    console.log(data);
    console.log('initData 执行完成');
    return data;
  }
   getData(){
    let url = 'https://tieba.baidu.com/hottopic/browse/topicList';
    let data = this.client.get(url).toPromise();
    console.log(data);
    console.log('getData 执行完成');
    return data;
  }
}

Angular请求同步async、await使用方式_第1张图片

你可能感兴趣的:(Angular,Angular)