我正在为实时图表创建一个角度指令,此处显示的代码将返回所有内容,包括link:function() { }内部指令。

这是完美运行的静态指令的代码

angular.module('app').directive("flotChartRealtime", [
    function() {
        return {
            restrict: "AE",
            link: function(scope, ele) {
                var realTimedata,
                    realTimedata2,
                    totalPoints,
                    getSeriesObj,
                    getRandomData,
                    getRandomData2,
                    updateInterval,
                    plot,
                    update;
                return realTimedata = [],
                    realTimedata2 = [],
                    totalPoints = 100,
                    getSeriesObj = function() {
                        return [
                            {
                                data: getRandomData(),
                                lines: {
                                    show: true,
                                    lineWidth: 1,
                                    fill: true,
                                    fillColor: {
                                        colors: [
                                            {
                                                opacity: 0
                                            }, {
                                                opacity: 1
                                            }
                                        ]
                                    },
                                    steps: false
                                },
                                shadowSize: 0
                            }, {
                                data: getRandomData2(),
                                lines: {
                                    lineWidth: 0,
                                    fill: true,
                                    fillColor: {
                                        colors: [
                                            {
                                                opacity: .5
                                            }, {
                                                opacity: 1
                                            }
                                        ]
                                    },
                                    steps: false
                                },
                                shadowSize: 0
                            }
                        ];
                    },
                    getRandomData = function() {
                        if (realTimedata.length > 0)
                            realTimedata = realTimedata.slice(1);

                        // Do a random walk
                        //console.log(realTimedata);
                        while (realTimedata.length < totalPoints) {

                            var prev = realTimedata.length > 0 ? realTimedata[realTimedata.length - 1] : 50,
                                y = prev + Math.random() * 10 - 5;

                            if (y < 0) {
                                y = 0;
                            } else if (y > 100) {
                                y = 100;
                            }
                            realTimedata.push(y);
                        }

                        // Zip the generated y values with the x values

                        var res = [];
                        for (var i = 0; i < realTimedata.length; ++i) {
                            res.push([i, realTimedata[i]]);
                        }

                        return res;
                    },
                    getRandomData2 = function() {
                        if (realTimedata2.length > 0)
                            realTimedata2 = realTimedata2.slice(1);

                        // Do a random walk

                        while (realTimedata2.length < totalPoints) {

                            var prev = realTimedata2.length > 0 ? realTimedata[realTimedata2.length] : 50,
                                y = prev - 25;

                            if (y < 0) {
                                y = 0;
                            } else if (y > 100) {
                                y = 100;
                            }
                            realTimedata2.push(y);
                        }


                        var res = [];
                        for (var i = 0; i < realTimedata2.length; ++i) {
                            res.push([i, realTimedata2[i]]);
                        }

                        return res;
                    },

                    // Set up the control widget
                    updateInterval = 500,
                    plot = $.plot(ele[0], getSeriesObj(), {
                        yaxis: {
                            color: '#f3f3f3',
                            min: 0,
                            max: 100,
                            tickFormatter: function(val, axis) {
                                return "";
                            }
                        },
                        xaxis: {
                            color: '#f3f3f3',
                            min: 0,
                            max: 100,
                            tickFormatter: function(val, axis) {
                                return "";
                            }
                        },
                        grid: {
                            hoverable: true,
                            clickable: false,
                            borderWidth: 0,
                            aboveData: false
                        },
                        colors: ['#eee', scope.settings.color.themeprimary],
                    }),
                    update = function() {
                        plot.setData(getSeriesObj()); // getting .data filled here perfectly
                        plot.draw();
                        setTimeout(update, updateInterval);
                    },
                    update();
            }
        };
    }
]);




我的HTTP请求代码无效

 getSeriesObj = function () {
     return [{
         data: getRandomData(function(res) {
             console.log(res) // getting array result here from http call but not returning to data:
             return res;
         }),
         lines: {
             show: true,
             lineWidth: 1,
             fill: true,
             fillColor: {
                 colors: [{
                     opacity: 0
                 }, {
                     opacity: 1
                 }]
             },
             steps: false
         },
         shadowSize: 0
     }, {
         data: getRandomData2(function (res) {
             return res;
         }),
         lines: {
             lineWidth: 0,
             fill: true,
             fillColor: {
                 colors: [{
                     opacity: .5
                 }, {
                     opacity: 1
                 }]
             },
             steps: false
         },
         shadowSize: 0
     }];
 },
 getRandomData = function (callback) {
     var authToken = window.localStorage.getItem('token');
     var url = $rootScope.apiPath + 'Elasticsearch/countget?token=' + authToken;
     var res = [];
     $http.get(url).then(function (result) {
         realTimedata = result.data;
         if (realTimedata.length > 0)
         //result = [10,22,33,11,32,88,77,66,21,90,92,98,99.9,88.8,76,66,56,88];
         for (var i = 0; i < realTimedata.length; ++i) {
             var y = realTimedata[i] + Math.random() * 10 - 5;
             if (y < 0) {
                 y = 0;
             } else if (y > 100) {
                 y = 100;
             }
             res.push([i, y]);
         }
         callback(res);
     });
 },


问题:

当我尝试以下代码时:

update = function () {
    //console.log(getSeriesObj());
    plot.setData(getSeriesObj()); // .data property gets undefined
    plot.draw();
    setTimeout(update, updateInterval);
}


函数getSeriesObj()返回对象的数组,这些对象将data属性返回给undefined的原因是什么?

我该如何解决?

注意:这与this question有很大不同。

最佳答案

什么时候做

data: getRandomData(function(res) {
    return res;
});


您将getRandomData的rValue分配给data

如您的帖子所述,getRandomData现在没有return语句,因此返回undefined

这里的主要问题是您希望plot.setData(getSeriesObj());工作synchronously

脚步


获取数据以填充plot
将数据设置为plot
画出来
再次更新值


现在,随着http请求异步工作,您将无法期望从getSeriesObj()检索值。您必须认为getSeriesObj现在可以异步工作,因此您只能使用在准备好使用资源时将触发的回调

所以更新方法变成

update = function () {
    var updateTime = +new Date;
    getSeriesObj(function(res){ // execute that stuff when ready
        plot.setData(res);
        plot.draw();
        setTimeout(update, Math.max(10, updateInterval - (+new Date - updateTime)) );
    });
}


getSeriesObj

getSeriesObj = function (callback) {
    getRandomData(function(res) {
        getRandomData2(function(res2){
            var data = [{
                data: res,
                lines: {
                    show: true,
                    lineWidth: 1,
                    fill: true,
                    fillColor: {
                        colors: [{
                            opacity: 0
                        }, {
                            opacity: 1
                        }]
                    },
                    steps: false
                },
                shadowSize: 0
            }, {
                data: res2,
                lines: {
                    lineWidth: 0,
                    fill: true,
                    fillColor: {
                        colors: [{
                            opacity: .5
                        }, {
                            opacity: 1
                        }]
                    },
                    steps: false
                },
                shadowSize: 0
            }];
            callback(data); // now the ressource obj is now ready to be used
        });
    });
}

关于javascript - 静态响应有效!虽然异步不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32495786/

10-11 17:38