我有一个小型的瓶子服务器,返回给定machineID的随机值,如下所示:

@app.route('/dataMachine')
@enable_cors
def simulatedMachineData():

    prevVals = {'machineID_1': 0,'machineID_2': 0, 'machineID_3': 0,}
    devVals = {'machineID_1': 5.3,'machineID_2': 2.1,'machineID_3': 7.1,}

    dictVals  = bottle.request.query.decode()
    machineID = dictVals.get('machine', '')
    if machineID not in devVals.keys(): return '-1'
    prevVals[machineID] += normal(scale=devVals[machineID])
    return str(prevVals[machineID])


这没有问题。

现在,我有一个AngularJS应用程序,该应用程序可以与此数据进行交互,如下所示:

var app = angular.module('testBidirection', []);

app.controller('tempCntrl', function ($scope, $http, $interval){

    /////////////////////////////////////////////////
    // Data to display and its update function
    $scope.data = {
        'machineID_1':'0',
        'machineID_2':'0',
        'machineID_3':'0',
    };

    var machineIDs = ['machineID_1', 'machineID_2', 'machineID_3'];
    $scope.machineID = 'machineID_1';

    $scope.getData = function(){
        for (var i = 0; i < 3; i++) {
                $scope.machineID = machineIDs[i];
                $http.get('http://localhost:8080/dataMachine?machine=' + $scope.machineID).success(function(data) {
                    $scope.data[ $scope.machineID ] = data;
                });
        };
    };


    //////////////////////////////////////////////////
    // Button controller. Use this controller to
    //      toggle the initiation of getting and
    //      stopping data retrieval ...
    $scope.buttonText = 'start Comm';
    $scope.toggleComm = function(){
        if ($scope.buttonText == 'start Comm') {
            $scope.buttonText = 'stop Comm';
            stop = $interval($scope.getData, 2*1000);
        } else {
            $scope.buttonText = 'start Comm';
            $interval.cancel(stop);
            stop=undefined;
        }
    };

});


我相信问题在于此功能内:

$scope.getData = function(){
    for (var i = 0; i < 3; i++) {
            $scope.machineID = machineIDs[i];
            $http.get('http://localhost:8080/dataMachine?machine=' + $scope.machineID).success(function(data) {
                $scope.data[ $scope.machineID ] = data;
            });
    };
};


当我运行此脚本时,只能看到最后一个机器ID发生了变化。脚本运行时在浏览器上的输出示例如下:

{"machineID_1":"0","machineID_2":"0","machineID_3":"2.37252542925"}


"machineID_3"的值每隔2秒钟便会更改一次,而"machineID_1" amd "machineID_2"的值仍保持为0。

从Python输出中可以看到,服务器每2秒收到一次正确的get请求,如下面的示例所示。

127.0.0.1 - - [22/Apr/2016 16:33:32] "GET /dataMachine?machine=machineID_3 HTTP/1.1" 200 14
127.0.0.1 - - [22/Apr/2016 16:33:34] "GET /dataMachine?machine=machineID_1 HTTP/1.1" 200 14
127.0.0.1 - - [22/Apr/2016 16:33:34] "GET /dataMachine?machine=machineID_2 HTTP/1.1" 200 14
127.0.0.1 - - [22/Apr/2016 16:33:34] "GET /dataMachine?machine=machineID_3 HTTP/1.1" 200 14
127.0.0.1 - - [22/Apr/2016 16:33:36] "GET /dataMachine?machine=machineID_1 HTTP/1.1" 200 13
127.0.0.1 - - [22/Apr/2016 16:33:36] "GET /dataMachine?machine=machineID_2 HTTP/1.1" 200 14
127.0.0.1 - - [22/Apr/2016 16:33:36] "GET /dataMachine?machine=machineID_3 HTTP/1.1" 200 13


我在范围界定规则中缺少什么吗?

资源:

瓶子服务器的全部内容:

import bottle
from bottle import response
from numpy.random import normal

import json
import pandas as pd

app = bottle.Bottle()

# the decorator
def enable_cors(fn):
    def _enable_cors(*args, **kwargs):
        # set CORS headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

        if bottle.request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)

    return _enable_cors

@app.route('/dataMachine')
@enable_cors
def simulatedMachineData():

    prevVals = {'machineID_1': 0,'machineID_2': 0,'machineID_3': 0,}
    devVals = {'machineID_1': 5.3,'machineID_2': 2.1,'machineID_3': 7.1,}

    dictVals  = bottle.request.query.decode()
    machineID = dictVals.get('machine', '')
    if machineID not in devVals.keys(): return '-1'
    prevVals[machineID] += normal(scale=devVals[machineID])
    return str(prevVals[machineID])


HTML文件的全部内容:

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Plotly Graph Plotter Directive for AngularJS - Demo</title>
    <script src="jquery.min.js"></script>
    <script src="angular.min.js"></script>
    <script src="app3.js"></script>
</head>
<body ng-app="testBidirection">

Testing the return Values ...
<div  ng-controller="tempCntrl">

    <button ng-click='toggleComm()'>{{buttonText}}</button>
    <hr>
    {{data}}
    <hr>
</div>

</body>
</html>

最佳答案

我可以在以下几行代码中看到几个问题。


  $ scope.machineID ='machineID_1';


为什么将它分配给$ scope变量?如我所见,您仅使用它将机器ID发送到循环内的服务器。如果您不在视图中使用此变量,则应按以下方法更正此错误。

var machineID = 'machineID_1';



  $scope.getData = function(){ for (var i = 0; i < 3; i++) { $scope.machineID = machineIDs[i]; $http.get('http://localhost:8080/dataMachine?machine=' + $scope.machineID).success(function(data) { $scope.data[ $scope.machineID ] = data; }); }; };


向服务器发送Http调用是异步的。因此,如果您像上面那样进行操作,您的代码可能会将3个http请求发送到machineId = 3的服务器。因为以异步方式,您的循环将在所有http调用发送之前完成执行。应按以下方式更正。而且,您还分配了服务器调用的响应,如下所示。


  $ scope.data [$ scope.machineID] =数据;


现在,由于http调用的异步行为,$ scope.machineID可能等于3。因此,即使您从所有3个机器IDS获得数据,实际上您也为machineId 3分配了值。

$scope.getData = function(){
    for (var i = 0; i < 3; i++) {

            $http.get('http://localhost:8080/dataMachine?machine=' + machineIDs[i]).success(function(data) {
                $scope.data[machineIDs[i]] = data;
            });
    };
};


更新

    $scope.getData = function(){
       for (var i = 0; i < 3; i++) {
        var machineId=machineIDs[i];
        $http.get('http://localhost:8080/dataMachine?machine=' + machineId).success((function(machineId) {
                 return function(data) {
                 $scope.data[machineId] = data;
               }
        })(machineId));
      }
    }

关于python - AngularJS Controller 仅更新部分数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36789243/

10-12 01:21