Angular - Service返回值,但不在app.config

时间:2017-03-12 03:04:22

标签: javascript angularjs

我想调用一个服务来从数据库中检索用户(当前是模拟数据,但它将来自数据库)并且当"时将该用户的信息发送到ProfileController。简介"状态被激活。调用该服务,但之后没有任何反应:在函数的then()catch()部分中没有进行任何操作。关于我应该做什么的任何想法?

(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: "richard@piedpiper.com", phone: 4085550011, pokemon: { isPresent: true, name: "eevee"}, icon: { isPresent: false, name: null} },
                { id: 2, name: "Erlich Bachman", email: "erlich@aviato.com", phone: 4155552233, pokemon: { isPresent: true, name: "celebi"}, icon: { isPresent: false, name: null} },
                { id: 3, name: "Gavin Belson", email: "gavin@hooli.com", 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;
        });
})();

1 个答案:

答案 0 :(得分:2)

因为你不在服务中使用promise,你的UserService.findById()中不会有任何Promise.then()或Promise.catch()。

您应该在服务中使用承诺。

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