angualr post 數據請求

數據請求 postjson

新建一個服務 瀏覽器

 1. ng g service services /+服務名app

 egng g service services/playerpost

  • 在此服務中進行設置
  1. 引入自帶組件以及註冊   
    import {HttpClient,HttpHeaders} from '@angular/common/http'
  2. 在export class PlayerService中寫入 
    httpOptions = {headers: new HttpHeaders({'content-Type':"application/json"})}
  3. 在constructor中進行聲明
     constructor(private http:HttpClient) { }
  4. 使用傳來的url值以及其餘的數據(後臺給定的值)
  5. 請求實例
  • 一個參數的實例
    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)
        }
      )
   }
相關文章
相關標籤/搜索