首先要引入 http
import { HttpModule } from '@angular/http';
imports: [ BrowserModule, HttpModule ],
然後在構造函數如注入http
constructor( private http: HttpClient ) { }
然後http請求的調用
①:帶參數的post(一定要使用URLSearchParams進行封裝)
getData() {
const d = new URLSearchParams();
d.append('para', 'value' );
d.append('para1', 'value' );
this.http.post( '地址' , d)
.map(res => res.json()) // (5)
.subscribe(data => {
alert(JSON.stringify(data));
}, err => {
console.error('ERROR', err);
});
②:帶參數的get請求
getData() {
const dates = {
'str': 123
};
this.http.get('地址' , {params: dates})
.map(res => res.json())
.subscribe(data => {
alert(JSON.stringify(data));
}, err => {
console.error('ERROR', err);
});
③:不帶參數的get請求
getData() {
this.http.get('/hello')
.map(res => res.json())
.subscribe(data => {
alert(JSON.stringify(data));
}, err => {
console.error('ERROR', err);
});
this.http.get('url')
.toPromise().then(res => {
console.log(res);
});
this.http.get('url')
.subscribe(res => {
console.log(res);
})