在Angular中使用HTTP模块来对REST API进行调用。在Typescript中使用async/await将访问HTTP服务变得更加简单。
下面是一个HTTP GET请求的示例:
import { HttpClient } from '@angular/common/http';
async function getSomething(url: string) { const res = await this.http.get(url).toPromise(); return res; }
调用这个函数时,可以使用它的返回值来执行一些其他操作:
const result = await this.getSomething('https://api.example.com/something'); console.log(result);
当然,在用上述方法时,需要先导入HttpClient模块,调用get函数并使用toPromise()将其转换为Promise对象。同时,为了使用上述函数,也需要将Angular的HttpClient服务添加到应用程序的构造函数中。