0

I have an angular 1.4 application where I have a service that encapsulates the communication with my backend. If I do something like following to return data from an endpoint. The Api service that I'm injecting encapsulates my $http ajax requests

function MyDataService(Api, $injector, $q, $log) {
    var self = this;
    function getAll(){
        return self.Api.get('/myData').then(function(data){
            self.data = data;
            return self.data;
        })
    }
    return self;
}

If I use this service method in a controller or other modules, Am I referencing directly that property? I mean, if I do a double binding in a controller and that variable change, self.data inside my service will change too? I think JS is using references by default.

Thank you very much

5
  • 1
    Is self your service or your controller? Commented Apr 20, 2017 at 7:13
  • 1
    My service. I will complete the code :) Commented Apr 20, 2017 at 7:14
  • Include $http for ajax call Commented Apr 20, 2017 at 7:20
  • @ManikandanVelayutham that is wrapped in my other Api service Commented Apr 20, 2017 at 7:21
  • oh ok. Then update that code also Commented Apr 20, 2017 at 7:22

1 Answer 1

1

Yeah. you are referring the controller variable. use angular copy to avoid this. try this

function getAll(){
    return self.Api.get('/myData').then(function(data){
        self.data = data;
        var retdata={};
        angular.copy(data, retdata)
        return retdata;
    })
 }

Sign up to request clarification or add additional context in comments.

1 Comment

Or I can return data directly instead self.data. Am I wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.