我有一个AngularJS服务,其代码如下。我制作了2个Promise,然后想要调用该服务的一个功能。但是,由于回调处于不同的范围,我无法继续。知道如何去做吗?
app.service "ServiceName", [
"AnotherService"
"MyService"
(AnotherService, MyService) ->
@dataFromA = []
@dataFromB = []
@mashupData = () ->
debugger
@getDatafromA = () ->
//getDataFromDBAndReturn
@mainServiceFunction = () ->
@getDatafromA().then (response) ->
@dataFromA = response
MyService.dataFromB().then (response) ->
@dataFromB = response
@mashupData() //Gives Undefined Error
return
]
理想情况下,在调用mainservicefunction时,我希望它从A获取数据,n B然后运行mashupData
,它使用@dataFromA
以及@dataFromB
。
我该怎么做?
答案 0 :(得分:2)
使用Function.prototype.bind绑定正确的上下文:
app.service "ServiceName", [
"AnotherService"
"MyService"
(AnotherService, MyService) ->
@dataFromA = []
@dataFromB = []
@mashupData = () ->
debugger
@getDatafromA = () ->
debugger
@mainServiceFunction = () ->
@getDatafromA().then ( (response) ->
@dataFromA = response
MyService.dataFromB().then ( (response) ->
@dataFromB = response
@mashupData()
).bind(this)
).bind(this)
]
答案 1 :(得分:2)
您不需要在coffeescript中使用.bind
- 它是语言的一部分。用->
箭头替换所有=>
箭头(普通JS函数)(维护this
的函数):
(AnotherService, MyService) ->
@dataFromA = []
@dataFromB = []
@mashupData = () =>
debugger
@getDatafromA = () =>
//getDataFromDBAndReturn
@mainServiceFunction = () =>
@getDatafromA().then (response) =>
@dataFromA = response
MyService.dataFromB().then (response) =>
@dataFromB = response
@mashupData() // Will corretly resolve `this`