Angular 2: how to update a service variable in a module component so that the variable in a lazy module is updated automatically?
Below is a link to the Plunker project. where there are two components, impatient and lazy, there is also a common service that is used on both components.
How do I update a service variable in a module component to automatically update a variable in a lazy module?
[Plunker example][1]
[1]: https://plnkr.co/edit/L2ypUQZiltSPXnLlxBoa?p=preview
source to share
You have this behavior due to the child injector creating a new instance of the service. To create one instance of a service for an application, you must use the method.forRoot()
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SomeComponent } from './other.component';
import { SharedModule } from './shared/index'
import { SomeService } from './some.service';
@NgModule({
imports: [CommonModule, SharedModule],
declarations: [ SomeComponent ],
exports: [ SomeComponent ]
})
export class OtherModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
// here you put services to share
providers: [SomeService]
}
}
}
// and in AppModule
@NgModule({
imports: [
CommonModule,
SharedModule,
OtherModule.forRoot()
],
declarations: [ SomeComponent ],
exports: [ SomeComponent ]
})
This will allow you to use one instance of SomeService in your components.
I have updated your plunker. Please take a look at the modified example
source to share
You can achieve this using Observable
. This observable is stored in your service, and another can subscribe
to this observable. Below is an example where I removed the standard Angular stuff to improve readability:
service.ts
@Injectable()
export class MyService {
// BehaviorSubject sends last known value when someone subscribes.
public isAuthenticated$ = new BehaviorSubject<boolean>(false);
changeAuthenticated() {
// broadcast true to all subscribers
this.isAuthenticated$.next(true);
}
}
component.ts
myService.isAuthenticated$.subscribe(authenticated => {
if (authenticated) {
// do stuff
}
});
So when isAuthenticated$
MyService changes, it runs for all subscribers. Please don't shoot if there are no subscribers.
More information on Observables: https://angular-2-training-book.rangle.io/handout/observables/using_observables.html
source to share