Angular Share Variable betwen $http.get and controller [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-11 13:54:39

问题


I can't pass the content of one variable inside $http.get() to outside of this method... it's always undefined.

I tested with $rootScope, but it didn't work.

controller('myControl', function ($scope, $http) {
    var content;

    $http.get('../Json/data.json').success(function (data, content) {
        content = data;
    }).error(function (data, status, headers, config) {
        $scope.dataJson = "ERROR";
    });

    console.log(content); 
});

回答1:


There are two problems here:

  • The content parameter in your success handler is shadowing the content variable in your controller.
  • You are trying to write content to the console before it has a value. This will not work because $http.get() is asynchronous.

To fix these problems:

  • Remove the content parameter. It serves no purpose.
  • Use the content variable inside your success callback.
controller('myControl', function ($scope, $http) {
    var content;

    $http.get('../Json/data.json').success(function (data) {
        content = data;

        console.log(content);
        $scope.dataJson = content;
    }).error(function (data, status, headers, config) {
        $scope.dataJson = "ERROR";
    });
});



回答2:


First of all, you don't wait for asynchronous $http.get() to finish so console.log() will always print out undefined.

Second, maybe you could think about using then() rather than success().
http://bit.ly/18xIHio

The following should work just fine for you.

/* JS */
app.controller('myControl', function($http) {
    var ctrl = this;

    $http.get('http://www.data.fi/data.json').then(function (response) {
        ctrl.content = response; // use response.data to get the payload
    }).catch(function (error) {
        ctrl.content = error;
    }).finally(function() {
        console.log(ctrl.content); 
    });
});

<!-- HTML -->
<div ng-controller="myControl as ctrl">{{ ctrl.content | json }}</div>



回答3:


Don't pass content in your parameters for success function. This is a global variable. Passing it would create scoping issues. Also use console.log both inside success function and outside it.



来源:https://stackoverflow.com/questions/28211842/angular-share-variable-betwen-http-get-and-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!