i'm blocked on my code on an async problem. I have 3 fct, 1 is called by my component and return a value:
getMenu(): Observable<Menu> {
this.recupUser();
return of(this.menu);
}
Here i call my function recupUser() which does an http get request, and i take my data in var :
recupUser() {
return this.loginService.recupConnectedUser().subscribe(
{
next: value =>{
this.User = value;
this.initMenu()
},
}
)
} My var User is used on initMenu() then i have to call this fct in my subscription to get value in User. Then in initMenu() i do an condition :
initMenu() {
if (this.User.es = '04840') {
this.menu = {
leftMenu: [
{title: 'Title 1', id: '1', role: '/URL1'},
{title: 'Title 2', id: '2', role: '/URL2'},
],
rightMenu: [
{icon:'profile',tooltip:'Profile', id:'profile', role:'/'},
]
};
} else {
this.menu = {
leftMenu: [
{title: 'Title1', id: '1', role: '/URL1'},
],
rightMenu: [
{icon:'profile',tooltip:'Profile', id:'profile', role:'/'},
]
};
} }
then i initialise my menu in this last fct. i've tried may things but i don't reach to wait that all finish to return my value. i have some difficulties with the asynchrone principe so any help may be welcome !
CodePudding user response:
use rxjs operator
interface Menus {
leftMenu: {title: string, id: string, role: string}[];
rightMenu: {icon:string,tooltip: string, id: string, role: string}[];
}
in class
initMenu(es: string): Menus {
return es === '04840' ?
{
leftMenu: [
{title: 'Title 1', id: '1', role: '/URL1'},
{title: 'Title 2', id: '2', role: '/URL2'},
],
rightMenu: [
{icon:'profile',tooltip:'Profile', id:'profile', role:'/'},
]
} :
{
leftMenu: [
{title: 'Title1', id: '1', role: '/URL1'},
],
rightMenu: [
{icon:'profile',tooltip:'Profile', id:'profile', role:'/'},
]
};
}
getMenu(): Observable<Menus> {
this.loginService.recupConnectedUser().pipe(
map(value => {
this.User = value;
this.menu = this.initMenu(value.es);
return this.menu;
})
);
}