get 请求
get.service.ts
ng g service get创建一个服务
//get.service.ts
const baseUrl = " https://www.easy-mock.com/mock/5cac9abdbf60940c8b889555/"
import {Injectable} from '@angular/core'
import {HttpClient} from '@angular/common/http'
@Injectable({
provideIn:'root'
})
export class GetService {
getSomething(){
return this.http.get(baseUrl+'mock',{observer:'response'})
}
constructor(private http:HttpClient){
}
}
Post 请求
//post.service.ts
const baseUrl = " https://www.easy-mock.com/mock/5cac9abdbf60940c8b889555/"
import {Injectable} from '@angular/core'
import {HttpClient} from '@angular/common/http'
//如果不需要自己设置请求头的话,可以不写,这是一个可选参数
const httpOptions ={
headers:new HttpHeaders({
'Content-Type':'application/json'
})
}
Injectable({
provideIn:'root'
})
export class PostService{
constructor(private http:HttpClient){
}
postGetSomething(){
return this.http.post(baseUrl+'upload',null,httpOptions)
}
}
然后在组件中引入
//admin.component.ts
import {Component} from '@angular/core'
import {GetService} from './get.service'
import {PostService} from './post.service'
@Component({})
export class AdminComponent implements OnInit{
ngOnInit(){
this.getService.getSomething().subscribe(res=>{
console.log(res)
console.log(res.headers)
consonel.log(res.body)
})
this.post.postGetSomething().subscribe(res=>{
console.log(res)
}
}
constructor(private getService:GetService,private post:PostService){
}
}