HTTP获取Angular 1.5组件

时间:2016-11-20 19:17:44

标签: javascript html angularjs

我正在尝试使用AngularJS的1.5组件。我有一个服务,使用$ HTTP获取我的JSON文件并返回promise。然后,我在组件控制器中解析promise并使用this.work将其分配给控制器上的值。虽然这不会显示在我的HTML页面中。我在代码中包含了注释,如果这令人困惑,可以更好地解释一下。

我的理解是,promise(在我的控制器中)的解析是异步发生的,但是一旦解决了,为什么我没有在视图中显示更新到变量$ctrl.work的更新。相反,我从来没有从变量中获得值。

    // Component
    (function () {
        angular.module('development')
            .component('pgDev', {
                templateUrl: 'app/development/development.template.html',
                controller: ['workList', function (workList) {

                    //this.work = 'HELLO WORLD'; // <- this shows up in the html if uncommented

                    workList.getWorkItems().then(function (d) {
                        console.log(d.test); // outputs: myjsonfile
                        this.work = d.test; // <- this doesnt show in the html
                    });

                }]
            })
    }());

    // HTTP Get Service
    (function () {
        angular.module("development").factory("workList", ["$http",
            function ($http) {
                return {
                    getWorkItems: function () {
                        return $http.get("data/worklist/worklist.json").then(function (d) {
                            return d.data;
                        });
                    }
                }
            }])
    })();

    // html
    workitems: {{$ctrl.work}}

1 个答案:

答案 0 :(得分:0)

您正在丢失执行上下文,这意味着回调函数中的this(如果没有)和组件控制器的实例。一个简单(现代)的解决方案是使用arrow function而不是普通的匿名:

workList.getWorkItems().then(d => {
    this.work = d.test;
});