从服务

时间:2017-01-24 01:45:46

标签: angularjs angularjs-1.6

我正在尝试学习新的组件语法。如果我静态地在控制器中设置用户变量它可以工作,我会看到页面上的数据。如果我尝试从服务获取相同的数据,则不会显示数据。在将其分配给this.user变量之后,我看到了当时承诺中的数据。

我创建了一个plunkr来向你展示我正在尝试的东西。

http://plnkr.co/BGXesnKBmQGUlVH33jNa

angular.module('myWebApp', ['myModule']);

angular.module('myModule', []);

angular.
    module('myModule').
    component('myComponent', {
        controller: ['myService', function myController(mySvc) {
            mySvc.getUser().then(function (data) { // This gets data but does not populate view. Why?!
                this.user = {
                    name: 'Joe',
                    last: 'Shmoe'
                };

                console.log(user); // Populated with data from service
            });

            // Comment out above and uncoment this and it works!
            // this.user = {
            //     name: 'Joe',
            //     last: 'Shmoe'
            // };

        }],
        template: 'Hello, {{ $ctrl.user.name }}!',
    });

angular.
    module('myModule').
    factory('myService', ['$timeout', function ($timeout) {
        function getUser() {
            // Simulate http get
            return $timeout(function() {
                return {
                    name: 'Joe',
                    last: 'Shmoe'
                };
            }, 1000);
        }

        return {
            getUser: getUser
        };
    }]);

2 个答案:

答案 0 :(得分:1)

正如llp指出的那样,this.user指向函数this,所以你需要做的是在函数外部的变量中定义this像这样的控制器(plunker):

angular.module('myWebApp', ['myModule']);

angular.module('myModule', []);

angular.
    module('myModule').
    component('myComponent', {
        controller: ['myService', function myController(mySvc) {
          var me = this;
            mySvc.getUser().then(function (data) { // This gets data but does not populate view. Why?!
                me.user = {
                    name: 'Joe',
                    last: 'Shmoe'
                };

                console.log(me.user); // Populated with data from service
            });

            // Comment out above and uncoment this and it works!
            // this.user = {
            //     name: 'Joe',
            //     last: 'Shmoe'
            // };

        }],
        template: 'Hello, {{ $ctrl.user.name }}!',
    });

angular.
    module('myModule').
    factory('myService', ['$timeout', function ($timeout) {
        function getUser() {
            // Simulate http get
            return $timeout(function() {
                return {
                    name: 'Joe',
                    last: 'Shmoe'
                };
            }, 1000);
        }

        return {
            getUser: getUser
        };
    }]);

答案 1 :(得分:1)

由于this中函数中的then变量与this的{​​{1}}不同,我建议您使用arrow function将保持controller不变以解决此问题:

this

updated plunker