【Angular2】http模块

上一个开始的例子做出来后,想把这个前端跟之前自己做的node的后端框架结合一下,看能不能实现登录注册

因为当初做node框架的时候就希望在前端改变的时候,后端能尽量少改动,这次直接把代码合起来

改了下package.json文件,改了下app.js里面的静态路径,以及将'/'指向为index页面,其他没动

【其实这步浪费了很多时间,因为路由总是匹配不上,报错500,找了很久没找到原因在哪儿,把error打出来才知道是app.use('/',routes)前面涉及到session方面的东西有错,于是把路由设置的语句调到前面,就ok了。。。。。。】

然后把ng2的前端,login的html页面,加入按钮事件,以及传入email和password的值

<input type="text" class="form-control" id="email" placeholder="Email" #newemail>

<input type="password" class="form-control" id="password" placeholder="Password" #newpassword>

<button (click)="login(newemail.value,newpassword.value)" class="btn" >提交 </button>

接下来比较悲伤的是component里面的login方法,重点是post方法,最重要的是参数如何传递,为此在github上找很多小例子看代码,以及谷歌搜,试了一些,但不成功

最终还是找到了,也不知道这算不算是标准的方法,但至少成功了

参考:http://www.it1352.com/192660.html

let bodys = JSON.stringify({ 'email': emails,'password':passwords});
let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
let requestoptions: RequestOptions = new RequestOptions({
method: RequestMethod.Post,
url: `/users/doLogin`,
headers: headers,
body: bodys
})

this._http.request(new Request(requestoptions)).map((response: Response) => response.json())
.subscribe(data => {
console.log(data);
});

map和subscr这里也折腾了很久,subscribe应该就像ng1里面的promise,可分别处理data和error的情况,或者说observable模式相当于promise,subscribe是它的订阅环节

而map的作用相当于数据处理,res => res.json() 等价于一个匿名函数: function(res){return res.json();},就是将res内容转换为json对象

原文地址:https://www.cnblogs.com/lww930/p/5579921.html