【问题标题】:How to call a factory method from another service method in angularjs?如何从angularjs中的另一个服务方法调用工厂方法?
【发布时间】:2015-04-10 15:48:17
【问题描述】:

我有一个工厂方法..

(function (angular) {
         "use strict";
          angular
        .module('app')
        .factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) {
       var markCurrentUserAsContentOwner = function () {
                    var user = getCurrentUser(true);
                    user.set('isContentOwner',"true");
                    user.save(null, {
                    success: function(savedUser) {
                       alert("succes"); 
                     },
                    error: function(savedUser,error) {
                         alert("error");
                    }
                });   

        };
 }]);

})(angular);

现在如果我从另一个服务方法调用这个方法..

(function(angular) {
'use strict';

angular
    .module('app')
    .service('ContentOwnerService',
    [
        '$q', 'UserService'
        function($q, userService) {
var servicemethod=function() {
userService.markCurrentUserAsContentOwner();//UserService is the factory name 
};
}]);

})(angular);

它显示一个错误..Uncaught TypeError: undefined is not a function。 请任何人帮助我解决此错误..

【问题讨论】:

  • 如果没有看到工厂的主体就很难判断,但我猜你只需要在你的工厂返回时暴露函数。
  • 你的工厂服务注入控制器了吗?
  • 请提供所有代码
  • 我已添加代码完整代码请查看

标签: javascript html angularjs interceptor factory-method


【解决方案1】:

使用$injector 服务来解决这个问题。 Example:

session.factory('redirectInterceptor', ['$injector','$rootScope', '$timeout', '$q', '$window', function($injector,$rootScope, $timeout, $q, $window) {
return {
    'request': function(req) {

        req.headers['CustomHeader'] = "Be Creative!";
        return req || $q.when(req);

    },
    'response': function(response) {
        if (response.data.Status === 'Failed...') {

            var AuthenticationService = $injector.get('AuthenticationService'); 
            AuthenticationService.ClearCredentials();

            $window.location.href = "/#/login";
            $timeout(function() {
                $rootScope.sessiondata = true;
            }, 5000)

            return $q.reject(response);
        } else {
            return response;
        }
     }
}}])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    相关资源
    最近更新 更多