2016-11-10 161 views
0

我創建了一個小項目,其中菜單和它的子菜單是從服務生成的。子菜單在主菜單被點擊時第一次加載,但下一次不加載。菜單和子菜單生成問題

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 
    } 
] 

這裏是問題:

enter image description here

任何意見將是有益的。謝謝。

回答

0

我認爲有在你的代碼中的一些其他問題,因爲你的MenuService實例應該在生命週期中產生的只有一次,如果它得到再次產生,那麼你可能會從它那裏得到空首先編輯constructor(private _menuService: MenuService)的,雖然這是不準確問題,但你可以通過菜單服務的構造函數console.log挖掘它是單身人士