Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to set global variable in subscribe function

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

like image 255
Gopal Singh Thakur Avatar asked Mar 05 '23 20:03

Gopal Singh Thakur


1 Answers

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.

Fix

Use the value only after the subscribe is invoked.

like image 127
basarat Avatar answered Mar 18 '23 04:03

basarat