简体   繁体   English

在AngularJS服务中共享数据

[英]Sharing Data in AngularJS Services

I've been using services in AngularJS to share data between controllers. 我一直在使用AngularJS中的服务在控制器之间共享数据。 In one particular service, I want to also expose some functionality to edit the shared object. 在一项特定的服务中,我还想公开一些功能来编辑共享库。 I created a simplified JSFiddle here: 我在这里创建了一个简化的JSFiddle:

http://jsfiddle.net/RichardBender/CQ6Z4/2/ http://jsfiddle.net/RichardBender/CQ6Z4/2/

angular.module('myApp', [])
.factory('myService', function() {
    return {
        mySharedObject:{
            myText:'abc'
        },
        updateObject: function() {
            console.log('function called');
            console.log(this);
            this.mySharedObject.myText = 'def';
        }
    };
})

I can see that the "this" when I call updateObject() is not the object literal that the service returns. 我可以看到,当我调用updateObject()时,“ this”不是服务返回的对象文字。 I realize that I could simply make this service depend upon another service that just exposes the shared data object, but is there a way to do so without creating a second service? 我意识到我可以简单地使该服务依赖于另一个仅公开共享数据对象的服务,但是有没有办法创建第二个服务呢?

Thanks, Richard 谢谢,理查德

The this keyword in javascript can be a bit confusing, as in most cases its value is determined by how the function was called. javascript中的this关键字可能有点令人困惑,因为在大多数情况下,其值取决于函数的调用方式。 There are many good articles on the internet that describes this behavior ( this one seems pretty good ). 互联网上有很多很好的文章描述了这种行为( 这看起来很不错 )。

I usually do something like this in my services - var myService in the service factory is now the same object that you can inject in your other services: 我通常在服务中执行类似的操作-服务工厂中的var myService现在与您可以在其他服务中注入的对象相同:

.factory('myService', function() {
  var myService = {
    mySharedObject:{
        myText:'abc'
    },
    updateObject: function() {
        console.log('function called');
        console.log(this);
        myService.mySharedObject.myText = 'def';
    }
  };
  return myService;
})

I've updated your example to show you how you get the expected value from this and a simple solution to how you can avoid using this : http://jsfiddle.net/sRb2N/ 我已经更新了你的例子来告诉你如何得到的预期值this和简单的解决方案,你如何避免使用thishttp://jsfiddle.net/sRb2N/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM