服务返回undefined到控制器

时间:2016-09-28 19:04:50

标签: javascript angularjs

这是我的服务:

'use strict';

    app
    .service('myService', function($http) {

        this.getJSON = function() {
            return $http.get('someUrl/dataForm').then(function(data){
                return data.result;
            });
        };
    });

在我的控制器中,我有:

'use strict'
        app.controller('myController', function ($scope, myService) {

            myService.getJSON().then(function(data){
                $scope.myData =data;
            });
            console.log($scope.myData);
        });

我可以看到http调用成功返回JSON值,但控制台日志显示myData的值未定义。 我做错了什么?

4 个答案:

答案 0 :(得分:3)

将console.log放在

 myService.getJSON().then(function(data){
                $scope.myData =data;
                console.log($scope.myData);
 });

DEMO

答案 1 :(得分:1)

更新控制器中的代码

'use strict';
app.service('myService', function($http) {
    this.getJSON = function() {
     return $http.get('someUrl/dataForm').then(function(data){
            return data.result;
        });
    };
});

控制器

  'use strict'
   app.controller('myController', function ($scope, myService) {
        myService.getJSON().then(function(data){
            $scope.myData =data;
           console.log($scope.myData);
        });
    });

答案 2 :(得分:1)

更改控制器的代码:

'use strict'
    app.controller('myController', function ($scope, myService) {

        myService.getJSON().then(function(data){
            $scope.myData =data;
            console.log($scope.myData);
        });

    });

这是因为getJSON是一个asycronous方法,getJSON方法的请求不会激发javascript等待响应,在" .then"中添加console.log。将解决您的问题。

顺便说一下,使用getJSON,你正在使用一个名为" promises"的概念,我给你一个关于$ http的链接解释

https://docs.angularjs.org/api/ng/service/$http

答案 3 :(得分:1)

  1. $ http.get()返回promise对象。
  2. promise对象有then(),catch(),finally()方法。
  3. 然后在成功时调用,在错误时捕获。

    将您的服务更改为

  4. app.service('myService', function($http) {
      this.getJSON = function() {
        return $http.get('someUrl/dataForm'); //returns promise object
      };
    });

    和控制器,

    app.controller('myController', function($scope, myService) {
      var promise = myService.getJSON();
      //after resolving then method get called
      promise.then(function(data) {
        $scope.myData = data;
        console.log($scope.myData);
      });
    });

相关问题