標籤:
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 請求)