I'm trying to build a shared service in an Angular 4 application, and am not able to maintain state for a variable.
I've created a Shared Service component with a public variable called showUpdateMessage which I want to set to true when a record has been saved:
import {Injectable} from "@angular/core";
@Injectable()
export class SharedService {
public showUpdatedMessage: boolean;
constructor() {
}
}
I then have an EditPerson component with a function that updates my SharedService :
@Component({
selector: 'person-edit',
templateUrl: './person-edit.html',
providers: [PersonService, SharedService]
})
export class PersonEditComponent {
person: Person;
constructor(
private personService: PersonService,
private sharedService: SharedService)
{
}
}
save(): void {
this.personService.updatePerson(this.person)
.then(() => {
this.router.navigate(['/admin/person']);
this.sharedService.showUpdatedMessage = true;
}
);
}
And then finally I have my PersonDetail component which looks to see whether showUpdateMessage is true:
export class PersonDetailComponent implements LoggedInCallback {
person: Person;
constructor(
private personService: PersonService,
private sharedService: SharedService)
}
ngOnInit(): void {
console.log(this.sharedService.showUpdatedMessage)
}
ngOnDestroy() {
this.sharedService.showUpdatedMessage = false;
};
}
My problem is that when I click Save on the EditComponent, ShowUpdateMessage is true, but reverts to Undefined when the PersonDetailComponent is loaded
Update
Here is my app.module.ts
import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from "@angular/core";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {PersonDetailComponent} from "./secure/people/person-detail.component";
import {PersonEditComponent} from "./secure/people/person-edit.component";
@NgModule({
declarations: [
PersonDetailComponent,
PersonEditComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
],
providers: [
SharedService],
bootstrap: [AppComponent]
})
export class AppModule {
}