I managed to create a dynamic menu based on user access right after logging in. I couldn’t explain when I asked what I really want in my angular 2 application. Yesterday I searched on the angular website that we can make 2 components communicative, so I found the following links:
https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html
Through the global emitter of events, we can do this. I share below:
GlobalEventManager:
import { Injectable, EventEmitter } from "@angular/core"; @Injectable() export class GlobalEventsManager { public showNavBar: EventEmitter<any> = new EventEmitter(); public hideNavBar: EventEmitter<any> = new EventEmitter(); }
The link below will help you understand how to implement the auth guard function (restrict user login without login).
http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial
Auth.Guard.ts:
import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { GlobalEventsManager } from "../_common/gobal-events-manager"; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private globalEventsManager: GlobalEventsManager) { } canActivate() { if (localStorage.getItem('currentUser')) { this.globalEventsManager.showNavBar.emit(true); return true; } else {
The model used in menu.component.ts
Features:
export class Features { Description: string; RoutePath: string; }
menu.component.ts:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Features } from '../_models/features'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { GlobalEventsManager } from "../_common/gobal-events-manager"; @Component({ selector: 'nav', templateUrl: './menu.component.html' }) export class MenuComponent { showNavBar: boolean = false; featureList: Features[] = []; private headers = new Headers({ 'Content-Type': 'application/json' }); constructor(private http: Http, private router: Router, private globalEventsManager: GlobalEventsManager) { this.globalEventsManager.showNavBar.subscribe((mode: any) => { this.showNavBar = mode; if (this.showNavBar = true) { <!-- the below function expects user id, here I have given as 1 --> this.getFeatureListByLoggedInUser(1) .then(list => { this.featureList = list; }); } }); this.globalEventsManager.hideNavBar.subscribe((mode: any) => { this.showNavBar = false; this.featureList = []; }); } private getFeatureListByLoggedInUser(userID: number): Promise<Features[]> { return this.http.get(your api url + '/Feature/GetFeatureListByUserID?userID=' + userID) .toPromise() .then(response => response.json() as Features[]) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('An error occurred', error);
Menu.Component.html:
<div id="navbar" *ngIf="showNavBar" class="navbar-collapse collapse navbar-collapse-custom"> <ul class="nav navbar-nav nav_menu full-width"> <li *ngFor="let feature of featureList" class="nav_menu" routerLinkActive="active"><a class="nav-item nav-link" [routerLink]="[feature.routepath]" routerLinkActive="active">{{feature.description}}</a></li> </ul> </div>
App.Component.ts:
<!-- menu container --> <nav> </nav> <!-- main app container --> <div class="container-fluid body-content-custom"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 no-padding"> <router-outlet></router-outlet> </div> </div> <footer class="footer"> </footer> In the last, we need to register the providers of menu and global event manager in app.module.ts app.module.ts /// <reference path="reset-password/reset-password.component.ts" /> /// <reference path="reset-password/reset-password.component.ts" /> import './rxjs-extensions'; import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpModule, XHRBackend } from '@angular/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AuthGuard } from './_guards/auth.guard'; import { ContentHeaders } from './_common/headers'; import { GlobalEventsManager } from "./_common/gobal-events-manager"; import { MenuComponent } from "./menu/menu.component"; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule, ReactiveFormsModule ], declarations: [ AppComponent, MenuComponent ], providers: [ AuthGuard, ContentHeaders, GlobalEventsManager ], bootstrap: [AppComponent] }) export class AppModule { }
Hope this helps!