Angular HTTPClient的使用方法

时间:2022-07-23
本文章向大家介绍Angular HTTPClient的使用方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这个例子演示了如何使用Angular的HttpClientModule.

在app.module.ts里导入HttpClientModule:

import { HttpClientModule } from ‘@angular/common/http’;

Add HttpClientModule to the AppModule @NgModule() imports array to register Angular’s HttpClient providers globally.

全局注册这个HttpClientModule:

Now that the AppModule imports the HttpClientModule, the next step is to inject the HttpClient service into your service so your app can fetch data and interact with external APIs and resources.

下一步则是在service中注入该HttpClient:

import { HttpClient } from ‘@angular/common/http’;

注意这一步从@angular/common/http中导入的HttpClient和前面app.module.ts导入的HttpClientModule不一样。

将HttpClient注入到Cart service的构造函数里:

在cart service cart.service.ts里 ,使用http读取price数据:

getShippingPrices() {
    return this.http.get('/assets/shipping.json');
  }