简体   繁体   中英

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. I'm confused as to how to update the bf object to be the new value. How would I reference myService.bf since this.bf would create a local instance for .success function?

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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