https://www.getpostman.com 下载postman
在编辑器中搜索rest.client插件
新建一个rest.http的文件
@baseUrl = https://jsonplaceholder.typicode.com
GET {{baseUrl}}/posts HTTP/1.1
###
POST {{baseUrl}}/POST HTTP/1.1
Content-Type: : application/json
{
"title":"这是一个测试的标题",
"body":"这是一个测试的内容",
"userId":1
}
Angular HttpClient
导入HttpClientModule
只在根模块中导入
整个应用秩序导入一次,不要在其他的模块导入
在构造中注入 HtppClient
get/post/putdelete 方法对应于Http方法
这些方法是泛型的,可以直接把放回的JSON转换成对应类型
不规范的请求,使用request
返回的值是Observablle
必须订阅,才会发送请求,否则不会发送
编辑器中配置rest client
首先在设置中搜索 restclient 找到这个
添加 配置环境变量
"rest-client.environmentVariables":{
"$shared": {
"iCode":"123456"
},
"dev":{
"host":"http://localhost:8080"
},
"prod":{
"host":"http://local.dev"
},
"imooc":{
"host":"http://apis.imooc.com/api"
}
}
按F1 搜索rest client 选择 switch environmentVariable 再选择自己配置的环境变量
在 environment.prod.ts中也要添加配置
在app.module.ts中引入HttpClientModule import { HttpClientModule } from '@angular/common/http'
在home.service.ts中
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { TopMenu, ImageSlider, Channel } from 'src/app/shared/components';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn:'root'
})
export class HomeService {
constructor(private http:HttpClient){}
getTabs(){
return this.http.get<TopMenu[]>(`${environment.baseUrl}/tabs`,{params:{key:`${value}`}})
}
getChannels(){
return this.http.get<Channel[]>(`${environment.baseUrl}/channels`,{params:{key:`${value}`}})
}
getImageSliders(){
return this.http.get<ImageSlider[]>(`${environment.baseUrl}/banners`,{params:{key:`${value}`}})
}
}
使用数据
this.service.getTabs().subscribe(tabs =>{
this.menus = tabs;
})
如果@component中添加changeDetection:ChangeDetectionStrategy.OnPush
this.service.getChannels().subscribe(channels => {
this.channels = channels;
this.cd.markForCheck();
})
this.service.getImageSliders().subscribe(imgs => {
this.imageSliders = imgs;
this.cd.markForCheck();
})