angular 中的 http 請求


angular 中使用 http 請求的前提,需要引入 httpClientModule 模塊

根模塊中 app.module.ts:

import { HttpClientModule } from '@angular/common/http'
 
imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],

組件中:

import { HttpClientfrom '@angular/common/http'

 

 constructor(public http: HttpClient) { }

 


1. GET 請求寫法:

getData() {
    let url = '/search/interface/getrelatequery?word=%E6%99%8B%E6%B1%9F'
    this.http.get(url).subscribe((res: any)=>{
      console.log("GET 請求"res)
      this.newsList = res.data.relateQuery
    })
  }

2. POST 請求寫法:

post 請求必須設置請求頭

import { HttpClientHttpHeaders } from '@angular/common/http'

 

postData() {
    let api = '/api/message/readnotice'
    let requestData = {
      advert_id: '212'
    }
    let headerOption = { headers: new HttpHeaders({ "Content-Type"'application/json'})}
    
    this.http.post(apirequestDataheaderOption).subscribe((res)=>{
      console.log("POST請求:"res)
    })
  }

3. jsonp 請求:

jsonp 請求與前兩種不同之處在與,除了引入 httpClientModule 之外,還要引入 HttpClientJsonpModule

根模塊中:

import { HttpClientModuleHttpClientJsonpModule } from '@angular/common/http'

組件中:

如果不引入 HttpClientJsonModule , this.http.jsonp 報錯

/**
   * jsonp 解決跨域
   * 使用 JSONP 格式請求數據的前提是 后台必須支持 jsonp 請求, 請求的 api 中帶有 callBack 或者 cb
   */
  getJsonpData() {
    let url = '/search/interface/getrelatequery?word=%E6%99%8B%E6%B1%9F'
    this.http.jsonp(url'callback').subscribe((res)=>{
      console.log("JSOP 請求數據"res)
    })
  }

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM