我试图在Angular 4应用程序中构建共享服务,并且无法维护变量的状态。
我创建了一个名为showUpdateMessage的公共变量的共享服务组件,我希望在保存记录时将其设置为true:
import {Injectable} from "@angular/core";
@Injectable()
export class SharedService {
public showUpdatedMessage: boolean;
constructor() {
}
}
然后我有一个EditPerson组件,其中包含一个更新我的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;
}
);
}
然后最后我有了PersonDetail组件,看看showUpdateMessage是否为真:
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;
};
}
我的问题是,当我在EditComponent上单击Save时,ShowUpdateMessage为true,但在加载PersonDetailComponent时恢复为Undefined
更新
这是我的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 {
}