0

I have I'm trying to write an AngularJS service which should work as singleton in storage files. There should be two methods:

  • for writing files by key getFilesForTabId
  • for getting saved files from setFilesForTabId

I'm trying to write something like this:

app.factory('fileStorage', ['LogService', function (LogService) {

    var fileStorage = {
        this.files = {};

      this.getFilesForTabId = function (key) {
          return this.files[key];
        };
        this.setFilesForTabId = function (key, files) {
            this.files[key] = files;
            return true;
        }
    }
    return fileStorage;

}]);

But this code is bad. There are errors when I'm trying using it. How could I write it? I'd grateful for help

Now I have a problem with getFilesForTabId function. I'm trying to run this function with undefined files[key] object. My actual service code is:

app.factory('fileStorage', ['LogService', function (LogService) {

    var fileStorage = {

        files: {},
        setFilesForTabId: function(key,files){

            this.files[key] = files;
            return true;

        },
        getFilesForTabId: function (key) {


            if(typeof(files[key]) === undefined) {

                return [];

            }
            else{

                return this.files[key];
            }
        }
    }
    return fileStorage;

}]);

Below I show error from browswer:enter image description here

Krzysztof Michalski
  • 791
  • 1
  • 9
  • 25

2 Answers2

1

You can't use = in {} object.

var fileStorage = 
{
   files: {},
   getFilesForTabId: function (key) {
       return this.files[key];
   },
   setFilesForTabId: function (key, files) {
       this.files[key] = files;
       return true;
   }
};
Ozgur
  • 3,738
  • 17
  • 34
1

you are trying to initialize fileStorage as an object but are writing it like a function instead. you need to use Object Initializer Syntax.

Try this instead:

app.factory('fileStorage', ['LogService', function(LogService) {

  var fileStorage = {
    files: {},

    getFilesForTabId: function(key) {
      return this.files[key];
    },

    setFilesForTabId: function(key, files) {
      this.files[key] = files;
      return true;
    },
  };

  return fileStorage;

}]);
Claies
  • 22,124
  • 4
  • 53
  • 77
  • Thanks. I've updated my post. Now I have a problem with running function getFilesForTabId with undefined files[key] object. Could you look on this? I've show screen with error from browser. I'd be very grateful ;) – Krzysztof Michalski Sep 05 '17 at 11:10