Reputation: 1694
I created a small project, where the menus and it's sub menus were generated from services. The sub menus are loading for the first time when a main menu is clicked, but the next time, it doesn't load.
app.component.html:
<li class="treeview" *ngFor="let menu of menus">
<a href="#" *ngIf="menu.ParentMenuId === 0">
<i class="fa fa-book"></i> <span>{{menu.Menu}}</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu" *ngFor="let submenu of menus">
<li *ngIf="submenu.ParentMenuId === menu.Id"><a routerLink="{{submenu.htmlId}}"><i class="fa fa-circle-o"></i> {{submenu.Menu}}</a></li>
</ul>
</li>
app.component.ts:
import { MenuService } from './services/menu.service';
...
export class AppComponent {
menus: any;
constructor(_menuService: MenuService) {
_menuService.getMenu().subscribe(menus => this.menus = menus);
console.log(this.menus);
}
}
menu.service.ts:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Global } from '../app.globals';
@Injectable()
export class MenuService {
constructor(private http: Http) { }
_data: any;
getMenu() {
return this.http
.get(Global.BASE_API_URL+'/api/menus/get/all')
.map(x => x.json())
}
}
and the json is
[
{
"Menu": "Master",
"ParentMenuId": 0,
"htmlId": "master",
"Id": 1,
"Code": null,
"IsActive": true,
"EnteredBy": 0,
"EnteredDate": null,
"UpdatedBy": null,
"UpdatedDate": null
},
{
"Menu": "Entity",
"ParentMenuId": 1,
"htmlId": "entity",
"Id": 2,
"Code": null,
"IsActive": true,
"EnteredBy": 0,
"EnteredDate": null,
"UpdatedBy": null,
"UpdatedDate": null
},
{
"Menu": "Entries",
"ParentMenuId": 0,
"htmlId": "entries",
"Id": 3,
"Code": null,
"IsActive": true,
"EnteredBy": 0,
"EnteredDate": null,
"UpdatedBy": null,
"UpdatedDate": null
},
{
"Menu": "Register",
"ParentMenuId": 3,
"htmlId": "register",
"Id": 4,
"Code": null,
"IsActive": true,
"EnteredBy": 0,
"EnteredDate": null,
"UpdatedBy": null,
"UpdatedDate": null
},
{
"Menu": "Patient",
"ParentMenuId": 3,
"htmlId": "patient",
"Id": 5,
"Code": null,
"IsActive": true,
"EnteredBy": 0,
"EnteredDate": null,
"UpdatedBy": null,
"UpdatedDate": null
}
]
Here is the issue:
Any advice would be helpful. Thank you.
Upvotes: 0
Views: 480
Reputation: 2068
I think that there is some other problem in your code because your MenuService
instance should be generated once in lifecycle only, if it get generated again then you would probably get null from it first of all edit constructor(private _menuService: MenuService)
although this is not exact problem but you can dig via console.log
in constructor of menuservice that it is singleton
Upvotes: 1