Maintaining a variable with a shared service in Angular 4
I am trying to create a generic service in an Angular 4 app and cannot maintain state for a variable.
I created a Shared Service component with a public variable called showUpdateMessage, which I want to set to true when the entry is saved:
import {Injectable} from "@angular/core";
@Injectable()
export class SharedService {
public showUpdatedMessage: boolean;
constructor() {
}
}
Then I 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;
}
);
}
Finally, I have my PersonDetail component that looks to see if 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 when I click Save in the EditComponent ShowUpdateMessage is true but falls back 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 {
}
+3
source to share
No one has answered this question yet
See similar questions:
or similar: