在Angular中有四種數據交互方式,分別是get請求數據,post提交數據,Jsonp請求數據和第三方模塊axios請求數據。
一、Angular get 請求數據
在app.modules.ts中引入HttpClientModule模塊並注入
import {HttpClientModule} from '@angular/common/http'
imports:[
BrowserModule,
HttpClientModule,
]
2.在要用到的地方引入HttpClient並在構造函數中聲明
import{HttpClient} from '@angular/common/http';
constructor(public http:HttpClient) { }
3.get請求數據
//這是接口地址
var api="http://www.baidu.com/api/homes";
this.http.get(api).subscribe(response =>{
console.log(response);
});
二、Angular post提交數據
1.在app.module.ts中引入HttpClientModule
import {HttpClientModule} from '@angular/common/http'
imports:[
BrowserModule,
HttpClientModule,
]
2.在用到的地方引入HttpClient,HttpHeaders並在構造函數中聲明HttpClient
import{HttpClient,HttpHeaders } from '@angular/common/http';
constructor(public http:HttpClient) { }
3.post提交數據
const httpPoint={
headers:new HttpHeaders({'Content-Type':'application/json'})
};
var api="http://127.0.0.1:4000/doLogin";
this.http.post(api,{username:‘小練’,age:'20'},httpPoint).subscribe(response =>{
console.log(response);
});