2017-03-12 72 views
0

我想調用服務以從數據庫中檢索用戶(當前模擬數據,但它將來自數據庫)並且具有在「配置文件」狀態激活時發送給ProfileController的用戶信息。該呼叫是對該服務進行的,但之後沒有任何反應:在該功能的then()catch()部分中未做任何操作。我應該做什麼的任何想法?Angular - 服務返回值,但不在app.config中路由

(function() { 
    "use strict"; 

    angular.module("testing_app", [ 
    "ui.router" 
    ]) 
    .config(function($urlRouterProvider, $locationProvider, $stateProvider, $qProvider) { 
    $locationProvider.html5Mode(true); 

    $stateProvider 
     .state("users", { 
      url: "/users", 
      templateUrl: "templates/users.html", 
      controller: "UsersController as uc" 
     }) 
     .state("profile", { 
     url: "/user/:id", 
     templateUrl: "templates/profile.html", 
     controller: "ProfileController as pc", 
     resolve: { 
      resolvedUser: ["UsersService", "$q", "$stateParams", function(UsersService, $q, $stateParams){ 
      console.log($stateParams.id); 
      return UsersService.findById($stateParams.id).then(function(user){ 
       return user; 
      }).catch(function(error){ 
       return $q.reject(error); 
      }); 
      }] 
     } 
     }); 
    }); 
})(); 

UsersService.js當前正在使用模擬數據,但它最終將從數據庫中獲取數據。

(function(){ 
    "use strict"; 

    angular.module("testing_app") 
     .factory("UsersService", function(){ 

      var Users = {}; 

      var userList = [ 
       { id: 1, name: "Richard Hendricks", email: "[email protected]", phone: 4085550011, pokemon: { isPresent: true, name: "eevee"}, icon: { isPresent: false, name: null} }, 
       { id: 2, name: "Erlich Bachman", email: "[email protected]", phone: 4155552233, pokemon: { isPresent: true, name: "celebi"}, icon: { isPresent: false, name: null} }, 
       { id: 3, name: "Gavin Belson", email: "[email protected]", phone: 9165554455, pokemon: { isPresent: true, name: "snorlax"}, icon: { isPresent: false, name: null} } 
      ]; 

      Users.all = function(){ 
       return userList; 
      }; 

      Users.findById = function(id){ 
       return userList.find(function(user){ 
        return user.id == id; 
       }); 
      }; 

      return Users; 
     }); 
})(); 
+0

你可以發佈你的UserService的細節嗎? – Pengyy

+0

@Pengyy現在檢查出來 –

+0

返回模擬的承諾,而不是模擬數據。 – georgeawg

回答

2

對於你沒有在服務中使用的承諾,不會有任何Promise.then()或Promise.catch()在你的UserService.findById()。

您應該在您的服務中使用承諾。

Users.findById = function(id){ 
    let deferred = this.$q.defer(); // you have to inject $q in your factory 

    deferred.resolve(userList.find(function(user) { 
     return user.id == id; 
    })); 

    return deferred.promise. 
}; 
+0

這樣做。我應該更清楚地知道,因爲過去我已經處理了許多承諾。非常感謝你。 –