为了账号安全,请及时绑定邮箱和手机立即绑定

angular2 - http模块作用域问题

angular2 - http模块作用域问题

月关宝盒 2018-10-17 13:22:46
最近在学习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条经验 获得超7个赞

好吧,参考了一下源码后得到启发,构造函数改写如下:

       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'!!!


查看完整回答
反对 回复 2018-11-16
  • 1 回答
  • 0 关注
  • 757 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号