1. 程式人生 > >關於angular http請求的操作

關於angular http請求的操作

首先要引入 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);

})