最近在学习angular2,写demo时用到其中的http模块,代码如下在http.get处理到subscribe()这里代码: console.log(res); return this.result = 'login';时,发现里面的this.result不是构造器里定义的this.result,而是subscribe()里自己重新定义的this.result,导致最后的console.log(this.result)一直输出‘hello world’.请问怎么在http请求后的处理函数中获取构造器定义的变量?
1 回答
慕田峪9158850
TA贡献1794条经验 获得超8个赞
好吧,参考了一下源码后得到启发,构造函数改写如下:
function (http,service) { var _self = this;
_self.result = 'hello world';
_self.httpService = http;
_self.loginService = service; // this.loginService = app.loginServiceInjector.get(app.loginService);
}login函数改写如下:
login: function (username) { var _self = this; //this.loginService.printName(username);
this.httpService.get('http://localhost:8080/xxx/login')
.map(function (res) { var str2 = JSON.parse(res._body);
return str2.message.securityMessage;
})
.subscribe(function (res) { console.log(_self.result);
return _self.result = 'login';
});两次运行login结果如下
第一次:'hello world'; 第二次:'login'
证明在subscribe里运行的函数可以成功拿到app.loginComponent下的变量定义。
结论:要善于利用'this'!!!
添加回答
举报
0/150
提交
取消
