如何重新启动ngOnInit以更新插值 [英] How to restart ngOnInit to update Interpolation
问题描述
是否可以在更改变量上重新启动ngOnInit()
Is there way to restart ngOnInit()
on change variable
因为我想在更改theme
变量时重新启动ngOnInit()
,
这是我的代码
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>
我在phraseColor
变量处遇到的问题
phraseColor
的默认值为蓝色
当我使用changeTheme()
更改theme
变量时,应该认为phraseColor
的值是橙色
when I change theme
variable using changeTheme()
It supposed to be the value of phraseColor
is Orange
但phraseColor
的值不会保持蓝色
但是,当我转到任何页面并返回此页面时,phraseColor
的值为橙色
However when I go to any page and return to this page the value of phraseColor
is Orange
我的问题是如何重新启动ngOnInit
来更新插值
My Question is how to restart ngOnInit
to update Interpolation
theme
变量 SettingsService.ts
export class SettingsService {
theme: string = '#3f51b5';
}
推荐答案
ngOnInit
是生命周期挂钩.它是由框架执行的,不应手动调用.该类应该重构为不需要.
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.
考虑到settingsService.theme
不会被任意更改,而只能通过changeTheme
进行更改,因此可以在此处更新值:
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;
}
如果希望settingsService.theme
在其他地方进行更改,则该服务需要RxJS可观察/主题才能通知订户:
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');
}
它可以在组件中订阅:
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');
}
这篇关于如何重新启动ngOnInit以更新插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!