i want to set service response in a variable for use in view my TS file is as follow
MenuService is custom service and geMenus() is function to fetch all menus from database
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { MenusService } from '../menus.service';
@Component({
selector: 'app-header1',
templateUrl: './header1.component.html',
styleUrls: ['./header1.component.css'],
providers:[MenusService]
})
export class Header1Component implements OnInit {
menus=['Login','Register','Subscribe'];
primeryMenus:any;
//menus1=['Home','Matches','Players','Teams','Tournaments','Contact Us','About Us'];
constructor(private translate: TranslateService,private _ser:MenusService) {
translate.setDefaultLang('en');
}
ngOnInit(){
this.getMenu();
}
getMenu(){
this._ser.getMenus().subscribe(res=>{
this.primeryMenus = res;
console.log(this.primeryMenus) // output is json object ( getting correct output )
});
console.log(this.primeryMenus) // output is undefined
}
switchLanguage(language: string) {
this.translate.use(language);
}
}
how to set primaryMenu in subscribe observable
Your code
this._ser.getMenus().subscribe(res=>{
this.primeryMenus = res;
console.log(this.primeryMenus) // output is json object ( getting correct output )
});
console.log(this.primeryMenus) // output is undefined
This is the fundamental nature of subscribe. The callback is executing after all the sync code is done.
Use the value only after the subscribe is invoked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With