在Angular 10中,可以使用async
和await
关键字来等待服务返回信息后再渲染。下面是一个示例:
data.service.ts
,用于获取数据:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData(): Promise {
return new Promise((resolve, reject) => {
// 模拟异步请求
setTimeout(() => {
resolve('Hello World');
}, 2000);
});
}
}
async
和await
来等待服务返回的数据:import { Component, OnInit } from '@angular/core';
import { DataService } from 'path/to/data.service';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
data: string;
constructor(private dataService: DataService) { }
async ngOnInit() {
this.data = await this.dataService.getData();
}
}
my-component.component.html
中使用data
属性来渲染数据:{{ data }}
这样,当组件初始化时,它会等待服务返回的数据后再渲染到模板中。在这个示例中,数据将在2秒后返回,并显示在模板中。