方案: 我有两个控制器,它们使用一个服务,第一个控制器可以调用搜索方法,当服务加载数据时得到结果,第二个只能被通知服务加载数据。
这是我的代码:
app.factory "searchService", ($resource, $q, $log) ->
resource = $resource("//localhost:8001/data/search/1")
searchSuccessDef = $q.defer()
searchSuccess: searchSuccessDef.promise
search: (scope, term) ->
def = $q.defer()
resource.get(
((content) ->
$log.info content
searchSuccessDef.notify()
def.resolve(content)
),
((response) ->
$log.warn response
def.reject(response)
)
)
def.promise
///
app.controller "navpanelController", ($scope, searchService) ->
$scope.search = (term) ->
searchResult = searchService.search(term)
searchResult.then (res) ->
console.log "!!!"
$scope.result = res
///
app.controller "contentController", ($scope, $q, searchService) ->
searchService.searchSuccess.then (content) ->
console.log "---"
但是这不起作用,因为searchSuccessDef.notify()
没有调用告示者searchService.searchSuccess.then (content) ->
,但如果我使用searchSuccessDef.resolve()
,则会触发一次承诺。
问题可能就在这里。 谢谢!
答案 0 :(得分:1)
我不熟悉CoffeesSript,但我可以告诉你的是,notify方法回调是then
方法的第3个参数
.then(function(greeting) { //Success
alert('Success: ' + greeting);
}, function(reason) { //Failure
alert('Failed: ' + reason);
}, function(update) { //notification
alert('Got notification: ' + update);
});