angular的httpClient

     angular使用httpClient模块发送网络请求,首先在app.module.ts中引入HttpClientModule、HttpClientJsonpModule相关模块,然后在下方imports中添加相关模块

import {HttpClient, HttpClientModule,HttpClientJsonpModule} from '@angular/common/http'

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,            //get/post
    HttpClientJsonpModule        //完成jsonp跨域
  ],

1、http请求---get和post

    在需要发送网络请求的组件中引入,注意post请求需要引入httpheaders;下方construuctor中定义变量

// 引入get请求,post请求需要加headers
import {HttpClient,HttpHeaders} from '@angular/common/http'


constructor(public http:HttpClient,public hr:HttpRequestService) { }

发送get/post请求

//get
getData(){
    let api = 'http://a.itying.com/api/productlist'

    this.http.get(api).subscribe(res => {
      // this.list = res.result
      console.log(res)
    })
}


//post
postData(){
    const httpOptions = {headers:new HttpHeaders({'content-type':'application/json'})}      //手动设置请求类型

    var api = ''
    this.http.post(api,{username:'张三',age:20},httpOptions).subscribe(res=>{

    })
}

2、jsonp请求

// jsonp请求,服务器必须支持jsonp
  getJsonpData(){
    // 实际请求路径在API后拼接callback
    var api = 'http://a.itying.com/api/productlist'
    this.http.jsonp(api,'callback').subscribe(res=>{
      console.log(res)
    })
  }

3、axios请求

在service里封装一个发送axios的请求

axiosGet(api:any){
    return new Promise(resolve => {
      axios.get(api).then(
        res => {
          resolve(res) 
        }
      ) 
    })  
}

  在需要发送axios请求的组件中引入,然后constructor中引入变量

import { HttpRequestService } from 'src/app/services/http-request.service';


constructor(public http:HttpClient,public hr:HttpRequestService) { }

// axios请求数据
  getAxiosData(){
    var api = 'http://a.itying.com/api/productlist'
    this.hr.axiosGet(api).then(res=>{
      console.log(res)
    })
  }

你可能感兴趣的:(angular,angular.js,前端)