angular2 学习笔记 ( Http 请求)

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...
});

 

文章来自:http://www.cnblogs.com/keatkeat/p/5814708.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3