简体   繁体   English

从函数内部修改Angular Factory对象

[英]Modifying Angular Factory Object from inside a function

This is the function that I am working with to call my factory 这是我正在打电话给我的工厂的功能

var myService = function($http) {
    return {
        bf: null,

        initialize: function() {
            this.promise = $http.get(this.server + "/requestkey").success(function(data) {
                myService.bf = new Blowfish(data.key);
            });
       }
}

And I am creating this object using 我正在使用创建此对象

TicTacTorrent.service('AService', ['$http', myService]);

However, when calling AService.initialize() it creates the promise object like it should, but it doesn't update the BF object. 但是,在调用AService.initialize()时,它会像应有的那样创建promise对象,但不会更新BF对象。 I'm confused as to how to update the bf object to be the new value. 我对如何将bf对象更新为新值感到困惑。 How would I reference myService.bf since this.bf would create a local instance for .success function? 我将如何引用myService.bf,因为this.bf将为.success函数创建本地实例?

Try this: 尝试这个:

var myService = function($http) {
    this.bf = null;
    return {
        bf: this.bf,

        initialize: function() {
            this.promise = $http.get(this.server + "/requestkey").success(function(data) {
                myService.bf = new Blowfish(data.key);
            });
       }
}

Where do you want to initialize? 您要在哪里初始化? Have you seen the $provider example code? 您看过$ provider示例代码吗? Search for "provider(name, provider)" and check if it suits your need. 搜索“提供者(名称,提供者)”,然后检查是否适合您的需求。

Otherwise I'm unsure what the code you'vew written will run like. 否则,我不确定您编写的代码将如何运行。

I usually write factories like this: 我通常这样写工厂:

angular.module('app').factory('myService', ['$http', function($http) {
    var publicObj = {};
    publicObj.bf = ""; // Just to make sure its initialized correctly.
    publicObj.initialize = function() {snip/snap... myService.bf = new Blowfish(data.key);};
    return publicObj;
}]);

The difference might be that you previous code returned an inline anonymous object which might have a hard time referring to itself. 不同之处可能在于您之前的代码返回了一个内联匿名对象,该对象可能很难引用其自身。 But by that logic it should work by just making myService return a predeclared var and returning that. 但是通过这种逻辑,它应该通过使myService返回一个预声明的var并返回它来工作。

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

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