0

I've created a service and have a lot of variables and functions. I want to inject this service into a few components but I want each component to update some of the service variables so when the components are called all the variables in the service will be updated with all the new values.

If i inject the service into a couple of components, is it the same service in all the components? (I mean the same reference of the service) or will it create a new reference each time the components are called?

Thanks!

alexexchanges
  • 3,252
  • 4
  • 17
  • 38
subt
  • 29
  • 1
  • 7
  • Possible duplicate of [Are Angularjs services singleton?](https://stackoverflow.com/questions/21496331/are-angularjs-services-singleton) – Mark Oct 02 '17 at 13:21

2 Answers2

1

I wasn't sure if the answer by @Zircon was what you were looking for so I will share my approach for what I think you want.

So presuming you imported your service in your app.module.ts and added it to your list of providers, in your service you can set something up like:

import { BehaviorSubject } from 'rxjs/Rx';
import { Injectable } from '@angular/core';

@Injectable()
export class YourService {
    public var1: BehaviorSubject<string> = new BehaviorSubject('str');
    public var2: BehaviorSubject<boolean> = new BehaviorSubject(true);
    public var3: BehaviorSubject<number> = new BehaviorSubject(123);

Now whenever a component changes one of these values, all other components can listen and stay updated by having something like this is your component:

export class YourComponent implements OnInit {
  myData: any = this.yourService.var1.subscribe((value) => this.myData = value);


  constructor(
    private yourService: YourService) { }

  ngOnInit() {
  }

}

You can update values by:

this.yourService.var1.next('new_str');

And if you want it so that when you load particular components they automatically update your service variables, you can place the above line within your ngOnInit(){} statement.

alexexchanges
  • 3,252
  • 4
  • 17
  • 38
0

You'll have a single instance of your Service injected into all of your components as long as you "provide" the service only once in your entire application. Typically, a "singleton" service will be declared in your CoreModule:

@NgModule({
  imports: [ 
    CommonModule,
    FormsModule,
    RouterModule,
    TranslateModule.forRoot({ //This is an ngx-translate module, it has a service that must be singular
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [Http]
      }
    })
  ],
  providers: [
    MySingletonService //This is your custom service that can be shared
  ],
  exports: [TranslateModule] // Expose the dependency module only once as well
})
export class CoreModule {
    ...
}

Then your AppModule (or whatever Module is part of your bootstrap) would import the CoreModule to make its Services available to your entire app. Note how this is different from a SharedModule, where each dependent Module will import the SharedModule and thus get a different instance of each declaration/provider within.

Zircon
  • 4,677
  • 15
  • 32
  • Thanks for the answer!. so why should i use SharedModule? do i put there only a components that i shared with other? for example the call for from component 1 and component 2 each time i call this line its create the a new component-three,i guess i should put a CaruselComponent in the sharedmodule and with the decorator (@input) to put the data i want that carusel to present. from a different component's but i dont need the ShardModule if i can just call and its anyway gonna get me a new reference of the carusel – subt Oct 02 '17 at 15:07
  • @subt I included a description of the `SharedModule` to show how you can purposefully (or accidentally) have multiple instances of a service in your application. If you want to have a singleton service, then it should be declared in your `CoreModule` which is imported into your `AppModule`. If you want a different instances for each module, then use a `SharedModule` which is imported by each module needing it. – Zircon Oct 02 '17 at 17:07