问题
Is there way to restart ngOnInit()
on change variable
Because I want to restart ngOnInit()
on change theme
variable,
this is my code
Settings.ts
export class SettingsPage implements OnInit{
phraseColor: string;
ngOnInit() {
let tch : {} = {'#3f51b5': 'Blue', '#ff9800': 'Orange'}
let ColorName = tch[this.settingsService.theme]; /* here my problem */
this.phraseColor = ColorName;
}
changeTheme(){
this.settingsService.theme = '#ff9800';
}
}
Settings.html
<div>Theme is {{ phraseColor }}</div>
<button (click)="changeTheme()">Change language</button>
My problem at phraseColor
variable
Default value of phraseColor
is Blue
when I change theme
variable using changeTheme()
It supposed to be the value of phraseColor
is Orange
But no the value of phraseColor
stay Blue
However when I go to any page and return to this page the value of phraseColor
is Orange
My Question is how to restart ngOnInit
to update Interpolation
theme
variable from this page SettingsService.ts
export class SettingsService {
theme: string = '#3f51b5';
}
回答1:
ngOnInit
is lifecycle hook. It is executed by the framework and isn't supposed to be called manually. The class should be refactored to not require that.
Considering that settingsService.theme
isn't changed arbitrarily but only with changeTheme
, values can be updated there:
ngOnInit() {
this.updateColor();
}
changeTheme(){
this.settingsService.theme = '#ff9800';
this.updateColor();
}
updateColor() {
let tch : {} = {'#3f51b5': 'Blue', '#ff9800': 'Orange'}
let ColorName = tch[this.settingsService.theme];
this.phraseColor = ColorName;
}
If settingsService.theme
is expected to be changed somewhere else, the service requires RxJS observable/subject in order to to notify the subscribers:
export class SettingsService {
theme: Subject = new BehaviorSubject('#3f51b5');
}
It can be subscribed in the component:
themeSubscription: Subscription;
ngOnInit() {
this.themeSubscription = this.settingsService.theme.subscribe(theme => {
let tch : {} = {'#3f51b5': 'Blue', '#ff9800': 'Orange'}
// immediate value is also available as this.settingsService.theme.value
let ColorName = tch[theme];
this.phraseColor = ColorName;
});
}
ngOnDestroy() {
this.themeSubscription.unsubscribe();
}
changeTheme(){
this.settingsService.theme.next('#ff9800');
}
来源:https://stackoverflow.com/questions/48568623/how-to-restart-ngoninit-to-update-interpolation