我有一个控制器:

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

    $scope.pageData = {};


    myService.promiseGetDataFromServer()
        .then(function (response) {
        $scope.pageData = response.data;

    }, function (reason) {
       // error has occurred.. etc...
    });
}


至此,一切正常。但是,我想根据某些确定性逻辑填充$scope.pageData。我尝试了这个:

app.controller('myController', function ($scope, myService2, thing) {

   $scope.pageData = {}

   switch (thing)
   {
       case 'whatever':
         myService2.promiseGetWhateverFromServer()
            .then(function (response) {
            $scope.pageData = response.data;

         }, function (reason) {
           // error has occurred.. etc...
         });
        break;

        case 'something':

          myService2.promiseGetSomethingFromServer()
              .then(function (response) {
              $scope.pageData = response.data;

           }, function (reason) {
              // error has occurred.. etc...
           });
           break;
   }

}


没有服务器错误,我记录了响应,一切都很好,但是由于我怀疑的属性未定义,因此我的视图无法呈现。

我该如何解决?我希望在该switch语句解决后加载视图。

最佳答案

如果我正确了,您可以通过选择适当的服务并进行请求来分离逻辑,如下所示:

app.controller('myController', function ($scope, myService2, thing) {

   $scope.pageData = {};

  //here we select service
  $scope.getDataForPageData = function(parameter){
    var serviceToSelect;

     switch (parameter)
     {
         case 'whatever':
           serviceToSelect = myService1;
          break;

          case 'another'
          serviceToSelect = myService2;
          break;
     }

     return serviceToSelect;

  }

  //do request and assign $scope.pageData when resolved
  $scope.getDataForPageData(thing).promiseGetSomethingFromServer()
        .then(function (response) {
            $scope.pageData = response.data;

        }, function (reason) {
           // error has occurred.. etc...
        });

}

关于javascript - Angular:Switch语句中的异步 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30466475/

10-14 19:27