保留 SailsJs 服务属性值
Retaining SailsJs Service property value
我有如下服务:
一些服务.js
module.exports = {
property:null,
foo:function(){
User.destroy({user_email:user.user_email}).exec(function(error,users){
this.property='somevalue'
});
}
}
当我像下面这样调用此服务时,它不会保留property
变量的值。
SomeService.foo();
console.log(SomeService.property) //returns null
如何使用 Sails 服务保留property
值?我如何像上课一样使用它?也许这更像是一个JavaScript问题,而不是Sails。我知道该对象与我使用它的方式不同,但是有没有办法让我可以将相同的对象用于服务?
:我已经更新了foo
,我认为在这种情况下this
是指destroy
构造而不是服务。
很明显,由于该功能
foo
,您正在null
正在调用异步方法。
foo:function(){
//the below functions is asynchronous so it is being pushed to event queue.
//and setting this.property='someValue' becomes asynchronous.
User.destroy({user_email:user.user_email}).exec(function(error,users){
this.property='somevalue'
});
};
所以在打电话时:
SomeService.foo();//this is asynchronous so does not block next executions.
console.log(SomeService.property)//this is not blocked by above call.
如果你想测试到底发生了什么。运行以下命令。
module.exports = {
property:null,
foo:function(){
User.destroy({user_email:user.user_email}).exec(function(error,users){
SomeService.property='somevalue';
console.log("Am i executed first???? Oh no I am the last among them");
});
}
};
而这:
SomeService.foo();
console.log(SomeService.property);
for(var i=2;i<10;i++)
console.log("I am called at number:",i);
所以我想你明白了它发生的原因。
相关文章:
- Ember服务在注入组件并在计算属性中使用后是未定义的
- 在Ember中,can服务具有计算属性
- 使用routeProvider中的服务属性
- 角度控制器不绑定服务对象属性 ng-repeat
- 提供“角服务”;TypeError:无法读取属性'helloConsole'“未定义”;
- 将服务中的函数绑定到$scope(错误:无法设置undefined的属性'onChange')
- 是否可以将服务注入Angular 1.5组件's templateUrl属性
- 使用angularjs中的自定义服务交换ng src属性
- 保留 SailsJs 服务属性值
- 当服务属性更改时,角度筛选器不会更新
- Angular JS:从服务响应中获取子属性
- 服务中的属性未更新
- 使用 $watch 在属性更改时执行$http调用的角度服务
- 角度 - 更改服务中的对象属性值,并在另一个控制器中使用它
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 角度 js 服务/工厂属性行为
- 通过 REST 设置属性的 AngularJS 服务无法正确设置
- 从 AngularJS 中的服务属性更新$scope
- AngularJS在从服务中获取对象属性后访问对象属性
- 谷歌应用程序脚本中的属性服务出现意外行为