我有一个作为coffeescript类编写的Angular服务。基础工作正常,但我很难添加$ timeout函数(应调用close方法):
class AlertService
constructor: ($timeout) ->
@timeout = $timeout
@alerts = []
getAlerts: -> @alerts
addAlert: (type, msg) ->
alert = {type: type, msg:msg}
@alerts.push alert
@timeout ****Can't work out what goes here ******
closeAlert: (alert) ->
@alerts = @alerts.filter (x) -> x isnt alert
AlertService.$inject = ['$timeout']
app.factory 'alertService', -> new AlertService
我尝试过的所有内容都会导致“未定义不是函数”错误。
有人能指出我正确的方向吗?
答案 0 :(得分:1)
看起来你需要的是服务而不是工厂。
尝试: -
class AlertService
@$inject = ['$timeout']
constructor: ($timeout) ->
@timeout = $timeout
@alerts = []
getAlerts: -> @alerts
addAlert: (type, msg) ->
alert = {type: type, msg:msg}
@alerts.push alert
@timeout (=> @closeAlert(alert)), 2000
closeAlert: (alert) ->
@alerts = @alerts.filter (x) -> x isnt alert
app.service 'alertService', AlertService
答案 1 :(得分:0)
看起来应该是这样的:
app.service 'AlertService', ['$timeout', class AlertService
constructor: (@$timeout) ->
@alerts = []
getAlerts: -> @alerts
addAlert: (type, msg) ->
alert = {type: type, msg:msg}
@alerts.push alert
#this could probably be written a little better, but should work
@$timeout ((alert) -> @closeAlert(alert)).bind(@, alert), 2000
closeAlert: (alert) ->
@alerts = @alerts.filter (x) -> x isnt alert
]
胖箭头(=>而不是 - >)会将您的this
实例绑定到clojure中。超时函数的回调在parens内部,第二个参数(超时长度)为2000
。
如果有疑问,我总是使用coffeescript-> js编译器来检查我的coffeescript。