angular2 學習筆記 ( Http 請求)

來源:互聯網
上載者:User

標籤:

refer : 

https://angular.cn/docs/ts/latest/guide/server-communication.html

https://xgrommx.github.io/rx-book/index.html

 

概念上沒什麼太多的區別.

下面記入一些例子和小區別 : 

 

不同的地方 : 

1.不支援 upload file (遊覽器的 xhr 可以很容易的通過 send formData 實現 ajax upload), ng2 沒有 

2.不支援 ng1 的 interceptor 攔截和 transformations (要自己實現可以試著繼承 http 服務來擴充)

3.預設結合rxjs (也可以很容易的轉化回熟悉的 Promise)

 

提醒: 

1.XSRF 和 ng1 一模一樣 

2.ng2 有一個記憶體 WebAPI 服務 ( in-memory web api service ),可以類比後端的 Web API 伺服器 

 

例子 :  

1.Headers and Params 

let headers = new Headers({ "myHeader": "myValue" });headers.append("yourHeader", "yourValue");let params = new URLSearchParams();params.set(‘myParam‘, ‘myValue‘);let options = new RequestOptions({ headers: headers, search: params });this.http.get("/api/products", options).toPromise().then((response) => {    console.log(response.json());}); 

 

2.POST

let body = JSON.stringify({    code : "mk200"});let headers = new Headers({ ‘Content-Type‘: ‘application/json‘ });let options = new RequestOptions({ headers: headers });this.http.post("/api/products", body, options).toPromise().then((response) => {    //do something...});

 

3.get CSV 

let options = new RequestOptions({ responseType: ResponseContentType.Text });this.http.get("/demo.csv", options).toPromise().then((response) => {    console.log(response.text());             }); 

 

4.by request 

let options = new RequestOptions({    method: RequestMethod.Post,    url: "/api/products",    headers: new Headers({ ‘Content-Type‘: ‘application/json‘ }),    body: JSON.stringify({ code: "mk200" })});this.http.request(new Request(options)).toPromise().then((response) => {    //do something...});

 

angular2 學習筆記 ( Http 請求)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.