簡體   English   中英

服務返回未定義的控制器

[英]Service returning undefined to the controller

這是我的服務:

'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的值未定義。 我究竟做錯了什么 ?

將console.log放在里面

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

演示

更新控制器中的代碼

'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);
        });
    });

更改控制器的代碼:

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

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

    });

發生這種情況是因為getJSON是一個異步方法,對getJSON方法的請求不會引起javascript等待響應,在“ .then”中添加console.log將解決您的問題。

順便說一句,使用getJSON時,您正在使用一個名為“ promises”的概念,我讓您通過$ http進行鏈接解釋

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

  1. $ http.get()返回Promise對象。
  2. Promise對象具有then(),catch(),finally()方法。
  3. 成功時調用,錯誤時捕獲。

    將您的服務更改為

 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); }); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM