angularjs从http json

时间:2017-07-03 17:33:34

标签: javascript angularjs json http

大家好我正在学习角度我写了一个简单的应用程序,但我不知道如何更新模型或视图,以后获取http json。

angular.module("dataApp",[])

.controller("ctrlData",function($scope,$http){
    $http.get('consulta.php')
    .success(function(data){
        //console.log(data);
        $scope.personas = data;
    }).error(function(error){
        console.log(error);
    }); });//end ctrl

consulta.php的输出

[
    {
        "id_persona":"1",
        "nombre":"sebastian",
        "apellido":"rincon ",
        "telefono":"4422404",
        "direccion":"calle 93 # 23 2132"
    },
    {
        "id_persona":"2",
        "nombre":"leiton",
        "apellido":"aricapa",
        "telefono":"4421112313",
        "direccion":"calle 634 supia avenia 93"
    },
    {
        "id_persona":"3",
        "nombre":"daniel",
        "apellido":"desconocido",
        "telefono":"645452423",
        "direccion":"urbanizacion los vientos 123"
    },
    {
        "id_persona":"4",
        "nombre":"angularjs",
        "apellido":"javascript",
        "telefono":"0231391",
        "direccion":"module controller 321"
    },
    {
        "id_persona":"5",
        "nombre":"mark",
        "apellido":"zuckerberg",
        "telefono":"423423423",
        "direccion":"palo alto california"
    }
]

的index.html

<tr ng-repeat="persona in personas">

            <td>{{persona.id_persona}}</td>
            <td>{{persona.nombre}}</td>
            <td>{{persona.apellido}}</td>
            <td>{{persona.telefono}}</td>
            <td>{{persona.direccion}}</td>
</tr>

一切正常但如果我在数据库中插入新行,mysql angularjs将不知道它,我需要刷新页面以查看新行。 另一方面,我尝试了setTimeout函数

setTimeout(function(){

    $http.get('consulta.php')
    .success(function(data){
        console.log(data);
        $scope.personas = data;
    }).error(function(error){
        console.log(error);
    });

},1000);

但我认为这不是正确的!请帮助谢谢。

2 个答案:

答案 0 :(得分:0)

您需要再次调用该服务才能更新视图。

当你在控制器中编写$http.get()调用时,它只在视图加载时调用一次。之后它没有被召唤。

您可以使用setInterval等定期调用您服务的内容。

angular.module("dataApp",[])
.controller("ctrlData",function($scope,$http){
    setInterval(function(){
        $http.get(...)
    }, 60000);
});

每分钟都会调用您的服务来更新您的观点。

但请注意,您不应该直接在控制器中使用$ http;而是使用服务。

答案 1 :(得分:0)

如果您希望Web应用程序对服务器端更改做出反应,您需要使用Web套接字或类似设备,或定期轮询API。我认为第一个(最好的)选项在这一点上对你来说可能有点过于复杂,所以留下第二个。

在开始实施此类内容之前,您必须确定实际上需要您的视图才能在没有用户交互的情况下对更改做出反应。为什么等待用户刷新(或改变路线)还不够?

无论如何,您可以通过以下方式创建服务来轮询API以获取数据:

angular.module('dataApp').service('personaService', PersonaService);

function PersonaService($http, $q, $interval){  
    var pollingInterval;

    this.getConsulta = getConsulta;
    this.startGetConsulta = startGetConsulta;
    this.stopGetConsulta = stopGetConsulta;

    function startGetConsulta(interval){
        if(pollingInterval){
            return $q.resolve();
        }
        var deferred = $q.defer();

        // Get first time
        getConsulta().then(function(data){
            deferred.notify(data);
        }, function(response){
            deferred.reject(response);
        });
        // Start polling
        pollingInterval = $interval(function(){
            getConsulta().then(function(data){
                deferred.notify(data);
            }, function(response){
                deferred.reject(response);
            });
        }, interval);

        return deferred.promise;
    }

    function stopGetConsulta(){
        if(angular.isDefined(pollingInterval)) {
            $interval.cancel(pollingInterval);
        }
        pollingInterval = null;
    }

    function getConsulta(){
        return $http.get('consulta.php')
            .then(function(response){ return response.data; } );
    }
}

要使用它,您将注入控制器并开始像这样的轮询:

angular.module("dataApp",[])
.controller("ctrlData",function($scope, personaService){

    personaService.startGetConsulta(60000).then(null, null, function(data){
        $scope.personas = data;
    });

});

请注意,由于我们使用notify代替resolve,对于服务返回的承诺,我们在使用承诺时使用第三个通知回调.then(..)功能。

应该这样做。但只是为了巩固一些事情 - 不要盲目地使用它。首先要确保你真的需要你的观点是这种反应。然后确保您真正了解上述示例中发生的情况。

Here's a plunker showing this in action