5

I have a service where I declare my variable. In my component I use this variable to put data into it.

Service:

@Injectable()
export class DataService {

    public msgs = [];

    constructor() { }       

}

Now I use this variable in my component:

export class MessagesComponent implements OnInit {   

    constructor(private dataService: DataService){}

    ngOnInit() {   
        this.getData();   
    }

    getData(){
        let msgs = [];

        if (diffr <= this.geomessage[i].range) {
            this.geomessage[i].dist = diffr;
            msgs.push(this.geomessage[i]);
            //console.log("this message: ", this.geomessage[i]); //DEBUG
        }
        this.dataService.msgs = msgs;

    }    
}    

I have only posted the necessary code.The this.dataService.msgs het filled with messages this works fine. When I got to another component the data of this.dataService.msgs still exists but when i Get back tot the Messagescomponent the this.dataService.msgs is undefined till i fill it again but I need the data that was in it. Does somebody know how to do this?

Thx

eko
  • 39,722
  • 10
  • 72
  • 98
user3356007
  • 393
  • 1
  • 6
  • 20

2 Answers2

11

If you are providing your DataService inside the providers array of your @Component annotation,

@Component({
    ...
    providers: [DataService],
})...

this service will be a singleton (it will create a new instance) for this component (and it's children if they have not provided this service under their annotation also).

If you want to use this service among multiple components and share the same instance of the service; you need to provide this service in a component/module which is the parent of these components in the DI tree. If this is a global service I suggest providing it only in your AppModule (or in a shared module).

@NgModule({
    providers:[DataService]
})

Source: https://angular.io/guide/dependency-injection#injector-hierarchy-and-service-instances

Angular 9 Update

Global level services are now defined as

@Injectable({
  providedIn: 'root',
})
export class DataService {

This should be the recommended approach since it will tree-shake itself if it's unused.

Source: https://angular.io/guide/providers#providedin-and-ngmodules

eko
  • 39,722
  • 10
  • 72
  • 98
  • did not add in the NgModule I will try that – user3356007 May 16 '17 at 10:15
  • @user3356007 also remove it from the `@Component` annotation – eko May 16 '17 at 10:17
  • How can i Use it in the component if i dont put it in the provider en constructor off the component? – user3356007 May 16 '17 at 10:22
  • @user3356007 no you need to put it on constructor just don't provide it in both `@NgModule` and `@Component`. Providing and injecting is 2 different things. – eko May 16 '17 at 10:23
  • I checked the doc (https://angular.io/guide/providers) and I didn't understood that the same instance is shared. I had a websocket in a service. When I reuse the component, my websockets where becoming one, the last one defined and I didn't know why. So you are totally right, but I can't find in the documentation where it says that is the same instance – Javier Oct 10 '19 at 14:30
  • 1
    @Javier, https://angular.io/guide/dependency-injection#injector-hierarchy-and-service-instances. This is the "good" version of the documentation. We had times where there were no documentation at all :) I agree that it's sometimes confusing – eko Oct 11 '19 at 07:34
3

Just a quick elaboration on echonax's reply, is that the provider works as a hierarchy. If you add it to app-module, it will work across the entire app, and therefore you shouldn't 'provide' it anywhere else. However, if don't need the service 'globally', just provide it on the parent component.