Después de mucho batallar pudimos dar con la contestación de este atasco que algunos los usuarios de este espacio tienen. Si tienes algún detalle que aportar puedes aportar tu información.
Solución:
Logré crear un menú dinámico basado en el acceso del usuario justo después de que el usuario inicia sesión. Creo que no pude articular el requisito correctamente en mi pregunta original. Ayer, mientras buscaba “cómo hacer que 2 componentes se comuniquen entre sí”, encontré esto en el sitio web de angular (ver enlace a continuación):
https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html
Podemos lograr esto mediante el uso de un EventEmitter global. Así es como lo implementé en mi código:
GlobalEventManager:
import Injectable, EventEmitter from "@angular/core";
@Injectable()
export class GlobalEventsManager
public showNavBar: EventEmitter = new EventEmitter();
public hideNavBar: EventEmitter = new EventEmitter();
El siguiente enlace le ayudará a comprender cómo implementar la protección de autenticación (restringiendo la entrada de un usuario sin iniciar sesión).
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
// not logged in so redirect to login page
this.router.navigate(['/login']);
this.globalEventsManager.hideNavBar.emit(true);
return;
Modelo utilizado en menu.component.ts
Características:
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)
this.getFeatureListByLoggedInUser(1)
.then(list => this.featureList = list; );
);
this.globalEventsManager.hideNavBar.subscribe((mode: any) =>
this.showNavBar = false;
this.featureList = [];
);
private getFeatureListByLoggedInUser(userID: number): Promise
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 error);
Menu.Component.html:
App.Component.ts:
In the last, we need to register the providers of menu and global event manager in app.module.ts
app.module.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
¡Espero que esto sea de ayuda!
Esto es lo que hago. Básicamente, el flujo se configura como un oyente en el componente de la aplicación que se suscribe a un observable de getLoggedIn. Cuando ese observable emite (el usuario inicia sesión), llamo al menú de inicio de sesión app.menu.service. Al cerrar la sesión, lo contrario es true y obtengo noLoginMenu.
servicio.menú.aplicación:
import RouterModule, RouterLinkActive, RouterLink from '@angular/router';
import Injectable from '@angular/core';
import Observable from 'rxjs/Observable';
import Subject from 'rxjs/Subject';
import Subscription from 'rxjs';
@Injectable()
export class AppMenuService
constructor()
getNoLoginMenu()
return [
label: 'Home',
routerLink: ['']
,
label: 'Documents',
routerLink: ['/document']
,
label: 'Calculator',
routerLink: ['/calculator']
,
label: 'Verify',
routerLink: ['/verify']
,
label: 'About',
routerLink: ['/about']
];
getLoggedInMenu()
return [
label: 'Home',
routerLink: ['']
,
label: 'Documents',
routerLink: ['/document']
,
label: 'Food',
routerLink: ['/food']
,
label: 'Calculator',
routerLink: ['/calculator']
,
label: 'Settings',
routerLink: ['/settings']
,
label: 'Themes',
routerLink: ['/themes']
,
label: 'About',
routerLink: ['/about']
,
label: 'Logout',
routerLink: ['/logout']
//command: (event: Event) => this.onLogout()
];
app.component.ts
export class AppComponent implements OnInit, OnDestroy
private items: MenuItem[];
appPageHeaderDivStyle: ;
selectedTheme: Theme;
errorMessage: string;
loggedIn: LoggedIn;
loggedInEmail: string = "";
isLoggedIn: boolean;
themeSub: Subscription;
loggedInSub: Subscription;
profileSub: Subscription;
constructor(
private as: AppMenuService,
private ts: ThemeService,
private ss: SettingsService,
private fs: FoodService,
private ls: LoginService)
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHander(event)
var shutdown = this.onShutdown();
//event.preventDefault();
ngOnInit()
this.themeSub = this.ts.getNewTheme()
.subscribe(
theme => this.selectedTheme = theme,
error =>
this.errorMessage = error
,
() => this.completeGetNewTheme()
);
this.ts.setTheme("Pepper-Grinder");
this.items = this.as.getNoLoginMenu();
this.ls.getLoggedIn()
.subscribe(
loggedIn =>
if (loggedIn.error != undefined && loggedIn.error === "" && loggedIn.email != "")
this.items = this.as.getLoggedInMenu();
var us = this.ss.getUserSettings();
if (us != undefined && us.theme != null && us.theme != "")
this.ts.setTheme(us.theme);
else
this.items = this.as.getNoLoginMenu();
this.ts.setTheme("Pepper-Grinder");
this.completeLoggedIn(loggedIn.email);
);
ngOnDestroy()
if (this.themeSub)
this.themeSub.unsubscribe();
if(this.loggedInSub)
this.loggedInSub.unsubscribe();
if(this.profileSub)
this.profileSub.unsubscribe();
completeLoggedIn(email: string)
this.loggedInEmail = email;
this.isLoggedIn = (this.loggedInEmail.length > 0);
completeGetNewTheme()
this.appPageHeaderDivStyle = this.ts.getAppPageHeaderDivStyle();
onShutdown(): boolean
var ok = true;
this.fs.completeUpdateDailyFood();
this.profileSub = this.ss.updateProfileInformation(this.ss.getUserSettings())
.subscribe(
status =>
console.log("logout - updated user");
,
error =>
ok = false;
,
);
return ok;
onLogout()
Servicio de inicio de sesión:
loginUser(localUser: LocalUser)
this.authSub = this.auth.loginUser(localUser)
.subscribe(
token =>
this.token = token
,
error =>
this.isLoggingIn = false;
var errorObject = JSON.parse(error._body);
this.errorMessage = errorObject.error_description;
console.log(this.errorMessage);
this.setLoggedIn( email: "", password: "", error: this.errorMessage );
,
() => this.completeLogin(localUser));
Reseñas y puntuaciones
Tienes la opción de proteger nuestra faena dejando un comentario o dejando una valoración te damos la bienvenida.