我创建了一个小项目,其中菜单及其子菜单是从服务生成的。单击主菜单时第一次加载子菜单,但下次加载时不会加载。
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())
}
}
和json是
[
{
"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
}
]
问题在于:
任何建议都会有所帮助。谢谢。
答案 0 :(得分:1)
我认为您的代码中还存在其他问题,因为您的MenuService
实例应该仅在生命周期中生成一次,如果它再次生成,那么您可能首先从它中获取null {{1虽然这不是确切的问题,但你可以通过菜单服务的构造函数中的constructor(private _menuService: MenuService)
挖掘它是单例