acostela
acostela

Reputation: 2727

Service get object null after init

I have a service which stores certain object to share it between different controller. In this case I have the following code

    $rootScope.$on('controller.event', function(event, arg){
          self.backendConnectorService.getBackendObject('99901').then(function(object){
        if(object) {
            self.myService.selectDeselectObject(object);
            console.log(self.myService.getCurrentObject());
            $state.go('myApp.mainArea.appsArea.objects.wizards');
        }
    });

When I have my object I go to that state that will need the object initialized. The problem is that when I load the controller for that state, when I do self.myService.getCurrentObject() returns null. When I execute the console.log in the above code I'm getting the correct object. Why is this? I thought that services were singletons.

Upvotes: 0

Views: 53

Answers (1)

rrd
rrd

Reputation: 5977

If you're trying to preserve data between states, you need to think in terms of using the built-in angular router or the 3rd party UI-Router (very popular, which I prefer). Then you can use resolves to resolve injections, or params to pass data along from one 'state' to another.

You're getting your 'object' then moving state - this initiates another controller, losing your object. Look at scotch.io's angular router page, which is quite helpful. You'd be better off using resolves in the state.config.js, then injecting it into your controller to use.

Upvotes: 1

Related Questions