2015-08-26 19 views
0

,爲提前感謝,請閱讀我的文章。Angularjs數據爲異步服務,範圍爲

我有一個服務,像這樣:

angular.module('myApp.services') 
.factory('myService', function($http, $q) { 
    var myService = { 
     getId: function() { 
      var defer = $q.defer(); 

      $http.get('http://xxxxxxxxxxxxxxxxxx/id/') 
      .success(function(data) { 
       defer.resolve(data); 
      }) 
      .error(function(data) { 
       defer.reject(data); 
      }); 

      return defer.promise; 
     }, 
     begin : function(jsonBegin) { 
      var defer = $q.defer(); 

      $http.post('http://xxxxxxxxxxxxxxxxxxxxxxx/begin/?format=json', jsonBegin) 
      .success(function(data) { 
       defer.resolve(data); 
      }) 
      .error(function(data) { 
       defer.reject(data); 
      }); 

      return defer.promise; 
     } 
    }; 

    return myService; 
}); 

父控制器(正常工作):

angular.module('myApp.controllers') 
.controller('controllerA', function($scope, myService) { 
    myService.getId() 
     .then(function(data) { 
      $scope.bID = data.bID; 
     }); 
}); 

而且孩子控制器:

angular.module('myApp.controllers') 
.controller('controllerB', function($scope) { 
    console.log($scope.$parent.bID); 
}); 

的價值的console.log對於BID是不確定的,你知道爲什麼嗎?我通過myService服務在父控制器中設置該變量。我想我的問題是由於異步調用,但我不確定。

謝謝。

+0

是的,你的猜測是正確的..但你想要做什麼? –

+1

是否metaApiService與myService相同?你是否想要在兩個地方改變它一樣? – lintmouse

+0

當調用console.log時,請求不是從服務器端口到達的。如果(metaApiService == myService)你的代碼很好。 – chfumero

回答

1

你可以做這樣的事情:

 angular.module('myApp.controllers') 
     .controller('controllerA', function($scope, myService) { 
      $scope.bID = myService.getId() 
       .then(function(data) { 
        return data.bID; 
       }); 
     }); 

    angular.module('myApp.controllers') 
     .controller('controllerB', function($scope) { 
      $scope.$parent.bID.then(function(bID) { console.log(bID); }); 
     }); 

子範圍將等待家長來解決的出價。當父bID已解決時,它將立即返回子範圍承諾中的值。雖然看起來有點凌亂。

另一種方法是在控制器加載之前解析myService請求。檢查了這一點:

http://www.codelord.net/2015/06/02/angularjs-pitfalls-using-ui-routers-resolve/

然後你就可以在父範圍設置爲解決價值和訪問它作爲子範圍普通財產。

+0

謝謝你@dustmouse,讓我檢查... – Sommer

+0

謝謝你!你的回答很有用。 – Sommer

0

問題是,控制器初始化時console.log代碼被執行,那時響應不會與父控制器上的結果一起到達。

試着把這段代碼放在你的測試控制器上。

angular.module('myApp.controllers') 
.controller('controllerB', function($scope, $timeout) { 

    // waith 1second for the server response on the parent controller 
    $timeout(function(){ 
     console.log($scope.$parent.bID); 
    }, 1000);   
}); 

僅供參考。這項工作console.log($scope.bID)檢查範圍繼承。

+0

可能的問題是,如果服務請求在超時期限內沒有返回。 – lintmouse

+0

@chfumero也謝謝你,讓我檢查一下你的代碼... – Sommer

+0

@dustmouse你是真實的,但這只是一個例子來檢查這裏發生了什麼。在更現實的場景中,必須提供某種解決方案來等待迴應。那是另一個問題。 – chfumero