0

I read a portion of code about creating a service in angularjs, I don't understand what "this" means in this situation (this.uploadFile = function (files))

recipesApp.service('uploadsService', function ($http) {
    var code = '';
    var fileName = '';

    this.uploadFile = function (files) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("image", files[0]);

        var promise = $http.post('/uploads/uploadFile.json', fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).then(function (response) {
                code = response.data.code;
                fileName = response.data.fileName;
                return{
                    code: function () {
                        return code;
                    },
                    fileName: function () {
                        return fileName;
                    }
                };
            });
        return promise;
    };
});
nam
  • 3,542
  • 9
  • 46
  • 68

2 Answers2

3

this points to the service itself.

recipesApp.service('uploadsService', function ($http) {

That function is a constructor. When called with new, what angular does, this refers to the created instance of the uploadsService.

this.uploadFile = function (files) {

So that line adds the method uploadFile to the uploadService.

a better oliver
  • 26,330
  • 2
  • 58
  • 66
0

It points to the function scope. Nothing special for an angular service.

In your specific case, it points to the function scope of your

function( $http ) {
    var code = '';
    ...
}

function. For example you can use this.code to access the code variable in the same scope.

However if you go into any inner function such as a callback, this will point to the scope of that function and you will not be able to point to parent variables using this.

With this.uploadFile = function(file){...} you are defining a function variable in the context, so that you access 'uploadsService' from another place in your application and you will be able to use

uploadsService.uploadFile();

harun
  • 1,889
  • 18
  • 19