[ Voting to avoid putting everything inside ngOnit
because I need to reuse the API response and model array in multiple functions. Need a way to reuse without cluttering up ngOnInit
.
I could simply call subscribe repeatedly in each function to solve the problem.
Tried other solutions on SO, but most suggest putting everything inside ngOnInit
. I prefer to keep only necessary functions there.
Please assist in creating a function for reusing API responses or initialized models like this.menu = data;
]
Attempting to display a menu from an API response.
Additionally, requiring the response to be used several times in different functions, facing null values outside of the subscribe
block.
Code snippet:
import { Component, OnInit } from '@angular/core';
// import { LoginModel } from "../../models/login/login-model";
import { MenuModel } from "../../models/menu/menu-model";
import { SubmenuModel } from "../../models/submenu/submenu-model";
// import { AccessModel } from "../../models/access/access-model";
import { MenuService } from "../../services/menu/menu.service";
import { SubmenuService } from "../../services/submenu/submenu.service";
@Component({
selector: 'app-admin-access',
templateUrl: './admin-access.component.html',
styleUrls: ['./admin-access.component.css']
})
export class AdminAccessComponent implements OnInit {
menu: MenuModel[] = null;
submenu: SubmenuModel[] = null;
constructor(private menuService: MenuService, private submenuSerive: SubmenuService) { }
ngOnInit(): void {
this.getMenu();
this.printMenu();
}
getMenu() {
this.menuService.GetAllMenu().subscribe((data: MenuModel[]) => {
this.menu = data;
console.log("first use : ");
console.log(data);
console.log("second use : ");
console.log(this.menu);
})
}
printMenu(){
console.log("third use : ");
console.log(this.menu);
}
}
Output :
https://i.stack.imgur.com/r7tMp.png
All responses are null from the printMenu()
function. Why is this happening? I subscribed and stored the value previously.
How can I permanently retain a value from an API response?