2016-12-31 90 views
2

我正在与fosrestbundle建立一个休息API,我管理与角和树枝模板的前端。一个在我的URL地址如下:

http://mywebsite/myroute/idContain 

当我打开网址在浏览器中,在树枝模板(一种HTML的),我检索参数“idContain”(从fosrestbundle控制器正在添加)与NG-INIT angularjs的是这样的:

<div class="container-fluid" ng-init="getContainByID({{ idContain }})"> 
    //...lot html div with angularjs directives 
</div> 

立时,NG-init将去我angularJS应用程序发现getContainByID(idContain)来运行它。 这一个看起来是这样的:

angular.module("myApp", ["ngSanitize", 'angular.filter', 'ui.tinymce', ...]) 
.config(function($interpolateProvider, ...) { 
    $interpolateProvider.startSymbol('{[{').endSymbol('}]}'); 
}) 
    .controller("myCtrl",function ($filter,..., myService) 
{ 
    // lot of code... 
    $scope.getContainByID = function(idContain) 
    { 

     $scope.currentContain = myService.getContains(idContain); 
     $scope.containRoot = $scope.currentContain.contain.containRoot; 
     ... 

    } 
    // lot of code... 
} 

事实是,myService.getContains(idContain)来自我休息服务看起来像这样:

angular.module("MyServiceRest", ['ngResource']) 

.factory("myService", function ($rootScope, $resource) { 


    var apiData = $resource(
     "/api", {}, 
     { 
      ... 
      "getContains": {method: 'GET', isArray: false, url: "mywebsite/api/myroute/:containid"} 
      ... 
     }); 

    return { 

     getContains: function (idContain) { 
      return apiData.getContains({containid: idContain}); 
     } 

    } 
}); 

现在的问题是,当我跑我angularjs应用,$范围.containRoot不会等到myService.getContains(idContain)(来自我的异步$资源服务)完成加载,并导致错误,导致我的web应用程序崩溃。

我该怎么办,强制$ scope.containRoot和其他角码的等待,直到myService.getContains(idContain)(连接到api资源)完成加载完成才能继续?

回答

1

$resource发出一个异步请求,但立即重新发送一个空的对象或数组。

有很多方法可以处理您的问题。

一个人不用担心在视图中声明$scope.containRoot和仅使用currentContain.contain.containRoot。收到

另一种是使用也由$resource返回$承诺,并在承诺回调指定范围属性的请求后,该属性将得到呈现

$scope.currentContain = myService.getContains(idContain); 

$scope.currentContain.$promise.then(function(){ 
     $scope.containRoot = $scope.currentContain.contain.containRoot; 
}); 

另一种方法是使用基于路由的决心在相同的承诺,所以路线(或状态,取决于路由器)是没有进入,直到请求完成

+0

得到这个错误试图做你做的:'angular.js:14328错误:[$注射器:unpr]未知提供者:$ promiseProvider < - $ promise < - myCtrl http://errors.angularjs.org/1.6.1/$injector/u npr?p0 =%24promiseProvider%20%3C-%20%24promise%20%3C-%20myCtrl at angular.js:68' – kabrice

+0

不应该得到那个,除非你将'$ promise'注入控制器, t做 – charlietfl

+0

是的,我做到了!我刚刚删除它,并且我得到了另一个错误: 'angular.js:14328 TypeError:无法在ChildScope $ scope中读取未定义的 的属性'then'。 getContainByID(http:// localhost:8000/js/angular-app/app.js:75:45)...' – kabrice

相关问题