要编写异步等待 Angular 示例,可以按照以下步骤进行操作:
npm install -g @angular/cli
ng new async-example
cd async-example
ng generate component AsyncExample
async-example.component.ts
文件中添加以下代码:import { Component } from '@angular/core';
@Component({
selector: 'app-async-example',
template: `
Async operation completed
`
})
export class AsyncExampleComponent {
showResult: boolean = false;
async startAsync() {
this.showResult = false;
await this.delay(2000); // 模拟异步操作
this.showResult = true;
}
delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
app.component.html
文件中使用该组件。将以下代码添加到文件中:
ng serve
http://localhost:4200
,点击 "Start Async" 按钮。将会看到 "Async operation completed" 文本在 2 秒后显示出来。这样,就完成了编写异步等待 Angular 示例的过程。