这个例子演示了如何使用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'); }