關於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);

})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章