數據請求 postjson
新建一個服務 瀏覽器
1. ng g service services /+服務名app
eg:ng g service services/playerpost
- 引入自帶組件以及註冊
import {HttpClient,HttpHeaders} from '@angular/common/http'
- 在export class PlayerService中寫入
httpOptions = {headers: new HttpHeaders({'content-Type':"application/json"})}
- 在constructor中進行聲明
constructor(private http:HttpClient) { }
- 使用傳來的url值以及其餘的數據(後臺給定的值)
- 請求實例
userCodeUrl:string = "xxx";
getUserCode(mobile: string):Observable<any>{this
return this.http.post(this.userCodeUrl, {mobile}, this.httpOptions)url
}spa
userCodeUrl:string = "xxx"; code
getUserCode(mobile: string, captcha: number) : Observable<any>{
return this.http.post(this.userCodeUrl, {mobile}, this.httpOptions)blog
}token
userCodeUrl:string = "xxx";
getUserCode():Observable<any>{
return this.http.post(this.userCodeUrl, {}, this.httpOptions)
}
在對應的文件ts中寫入
import { PlayerService} from '../../player.service';
constructor(private playerService: PlayerService) {}
數據進行請求
this.playerService.getPhoneUrl(this.mobile, this.codeNumber).subscribe(
res =>{
console.log(res)
if (parseInt(res.code) === 200) {
this.phonePup = false
this.tokenUtil.setToken(res.data.token) 這裏是給token從新設置值,在上面有講解token的更新問題
this.initData()
}
}
)
parseInt(res.code) === 200) 這裏獲取的res.code就是獲取到的返回碼,判斷返回碼是否等於200,是就會執行下列的代碼
註釋:post發送數據返回碼在瀏覽器的network下查看數據
eg2:沒有參數傳遞的狀況下
getgift(){
this.playerService.getGetGiftList().subscribe(
res =>{
console.log(res)
}
)
}