【问题标题】:Angular1: Factory.method is not a functionAngular1:Factory.method 不是函数
【发布时间】:2016-07-10 20:33:04
【问题描述】:

我在咖啡脚本中有一个像这样的角度工厂:

angular.module('app').factory 'appFactory', ['$q', 'Api', 'Flash', ($q, Api, Flash) ->

    obj = undefined

    get = ->
        if angular.isDefined(obj)
            return $q.when(obj)

        Api.AppInitializer.query().$promise.then ((response) ->
            obj = response
            return obj
        )
    { 
        get: get()
    }
]

我从这样的控制器中调用它:

angular.module('app').controller 'appCtrl', ($scope, appFactory) ->

  appFactory.get.then ((data) ->
    $scope.obj = data
    )

基本上我从工厂获取数据,如果数据当前未定义,我将发出 Api 请求来获取数据。这按预期工作。


现在我需要将令牌参数传递给工厂以获取特定记录:

angular.module('app').factory 'appFactory', ['$q', 'Api', 'Flash', ($q, Api, Flash) ->
    obj = undefined

    get = (token) ->
        if angular.isDefined(obj)
            return $q.when(obj)

        Api.AppInitializer.get(token: token).$promise.then ((response) ->
            obj = response
            return obj
        )
    { 
        get: get()
    }
]

我从这样的控制器中调用它:

angular.module('app').controller 'appCtrl', ($scope, appFactory) ->

  token = $scope.current_user.token_id

  appFactory.get(token).then ((data) ->
    $scope.obj = data
    )

现在我得到了错误

TypeError: appFactory.get 不是函数

如何将 token 参数传递给 appFactory.get?

【问题讨论】:

    标签: javascript angularjs coffeescript


    【解决方案1】:

    当数据存在时,您错过了返回Api.AppInitializer 方法的承诺。

    代码

    get = (token) ->
        if angular.isDefined(obj)
            return $q.when(obj)
        //return promise so that you can put .then inside controller.
        return Api.AppInitializer.get(token: token).$promise.then ((response) ->
            obj = response
            return obj
        )
    //return factory object as well
    return { 
        get: get //assign reference of get method here.
    }
    

    【讨论】:

    • 感谢 Pankaj,将 get: get() 更改为 get: get 不带括号的工作。
    • @Ryan.lay 我的回答中也有同样的事情
    • 是的,这就是我接受你的回答的原因 =)。您认为查理的答案是编写此函数的更好方法吗?我完全不熟悉 $q 的工作原理
    • @Ryan.lay 我们都有相同的代码结构.. 但他错过了缓存逻辑.. 由您决定哪个答案更好。但我始终尊重他个人的回答
    【解决方案2】:

    几个问题。

    1. 当您将 get() 分配给 返回对象
    2. 只有在 obj 未定义时才返回 Promise

    您可以存储请求承诺并返回,而无需使用$q

    angular.module('app').factory 'appFactory', ['$q', 'Api', 'Flash', ($q, Api, Flash) ->
        promise = undefined
    
        get = (token) ->
            if !angular.isDefined(obj)
             promise = Api.AppInitializer.get(token: token).$promise
    
            return promise
        { 
            get: get
        }
    ]
    

    我不喝咖啡,所以语法可能有点不对

    【讨论】:

    • 谢谢 Charlie,您的代码一开始就可以正常工作,但 Pankaj 先回答了,所以我必须接受他的回答。感谢您更正我的代码,我已经摆脱了多余的 $q。
    • @PankajParkar 是的,obj 用于缓存控制器之间的数据
    猜你喜欢
    • 2017-11-12
    • 2017-08-10
    • 2017-04-29
    • 2018-04-16
    • 2017-12-04
    • 2017-01-29
    • 2017-02-26
    • 2017-05-06
    • 2019-12-20
    相关资源
    最近更新 更多