在 app.module.ts 中引入 HttpClientModule 並注入ios
import {HttpClientModule} from '@angular/common/http'; imports: [ BrowserModule, HttpClientModule ]
Angular get 請求數據
在用到的地方引入 HttpClient 並在構造函數聲明npm
import {HttpClient} from "@angular/common/http"; constructor(public http:HttpClient) { }
get 請求數據json
var api = "http://a.itying.com/api/productlist"; this.http.get(api).subscribe(response => { console.log(response); });
Angular post 提交數據
在用到的地方引入 HttpClient、HttpHeaders 並在構造函數聲明 HttpClientaxios
import {HttpClient,HttpHeaders} from "@angular/common/http"; constructor(public http:HttpClient) { }
post 提交數據api
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; var api = "http://127.0.0.1:3000/doLogin"; this.http.post(api,{username:'張三',age:'20'},httpOptions).subscribe(response => { console.log(response); });
Angular Jsonp 請求數據
在 app.module.ts 中引入 HttpClientModule、HttpClientJsonpModule 並注入app
import {HttpClientModule,HttpClientJsonpModule} from '@angular/common/http'; imports: [ BrowserModule, HttpClientModule, HttpClientJsonpModule ]
在用到的地方引入 HttpClient 並在構造函數聲明ide
import {HttpClient} from "@angular/common/http"; constructor(public http:HttpClient) { }
jsonp 請求數據函數
var api = "http://a.itying.com/api/productlist"; this.http.jsonp(api,'callback').subscribe(response => { console.log(response); });
Angular 中使用第三方模塊 axios 請求數據
安裝 axiospost
cnpm install axios --save
用到的地方引入 axiosjsonp
import axios from 'axios'; axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed });
封裝service做爲http服務
import { Injectable } from '@angular/core'; import axios from 'axios'; @Injectable({ providedIn: 'root' }) export class HttpserviceService { constructor() { } axiosGet(api){ return new Promise((resolve,reject)=>{ axios.get(api) .then(function (response) { // handle success resolve(response) }); }) } }