在 Ionic 5 中动态更改侧边菜单项
Change side menu items dynamically in Ionic 5
我正在将一个项目从 ionic 3.2 迁移到 5.14,我在使用 observables 而不是事件时遇到了问题。
原代码中,用户登录后,我通过事件更改了sidemenu的名称和图片:
app.component.ts
this.events.publish('user:login', this.nomePrimeiro, Date.now());
this.events.publish('image:login', this.imagem, Date.now());
和 app.component.ts 我写了这个:
events.subscribe('user:login', (user, time) => {
Global.nomePrimeiro = user;
});
events.subscribe('image:login', (image, time) => {
Global.imagem = image;
});
如何为 Observables 改变这个?
我需要服务吗?
创建事件服务。
在 EventService.ts:
export class EventService {
private dataObserved = new BehaviorSubject<any>('');
currentEvent = this.dataObserved.asObservable();
constructo(){}
publish(param):void {
this.dataObserved.next(param);
}
}
用于发布示例页面 1 中的事件:
constructor(public eventService:EventService){}
updatePost(){
this.eventService.publish('post:updated');
// or
this.eventService.publish({name: 'postupdate', value: 'value you need to pass'});
}
在第 2 页中:
constructor(public eventService:EventService){
this.eventService.currentEvent.subscribe(data=>{
// here you can get the data or do whatever you want or data.name or data.value
});
}
我正在将一个项目从 ionic 3.2 迁移到 5.14,我在使用 observables 而不是事件时遇到了问题。
原代码中,用户登录后,我通过事件更改了sidemenu的名称和图片:
app.component.ts
this.events.publish('user:login', this.nomePrimeiro, Date.now());
this.events.publish('image:login', this.imagem, Date.now());
和 app.component.ts 我写了这个:
events.subscribe('user:login', (user, time) => {
Global.nomePrimeiro = user;
});
events.subscribe('image:login', (image, time) => {
Global.imagem = image;
});
如何为 Observables 改变这个? 我需要服务吗?
创建事件服务。 在 EventService.ts:
export class EventService {
private dataObserved = new BehaviorSubject<any>('');
currentEvent = this.dataObserved.asObservable();
constructo(){}
publish(param):void {
this.dataObserved.next(param);
}
}
用于发布示例页面 1 中的事件:
constructor(public eventService:EventService){}
updatePost(){
this.eventService.publish('post:updated');
// or
this.eventService.publish({name: 'postupdate', value: 'value you need to pass'});
}
在第 2 页中:
constructor(public eventService:EventService){
this.eventService.currentEvent.subscribe(data=>{
// here you can get the data or do whatever you want or data.name or data.value
});
}