Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input variable in a router-outlet component

Tags:

angular

I wanted to know if you guys now a way to have the @Input + ngOnChanges() combination or something doing the same inside a component in .

Basically, I have set a logged: boolean variable in my AppComponent and in my template I have :

<router-outlet></router-outlet>
<login [logged]="logged"></login>

What I want is to be able to watch that logged variable inside a component in the router-outlet so I make stuff here only when logged is as set as true.

I've tried to put <router-outlet [logged]="logged"></router-outlet> but that doesn't work, and using a variable in a service seems not to fit the ngOnChanges() watch.

Has anyone an idea ? Thanks !

like image 735
Guigui Avatar asked Sep 01 '16 10:09

Guigui


1 Answers

Create a service that has an observable to subscribe to

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ReplaySubject } from 'rxjs/ReplaySubject';

@Injectable()
export class UserSessionService {

  private _loggedIn: ReplaySubject<boolean> = new ReplaySubject<boolean>();

  public logUserIn() {
    this._loggedIn.next( true );
  }

  public logUserOut() {
    this._loggedIn.next( false );
  }

  public getUserLoggedInObs(): Observable<boolean> {
    return this._loggedIn.asObservable();
  }

}

Add the service to a parent module (be careful if adding it to multiple modules as you may get different instances of this service with different loggedIn values)

import { NgModule } from '@angular/core';
import { UserSessionService } from 'wherever/service/is/located';

@NgModule({
  providers: [ UserSessionService ]
})

export class AppModule { }

In your controller do something like

public userLoggedInObs: Observable<boolean>;
constructor( private userSessionService: UserSessionService ) {
  this.userLoggedInObs = userSessionService.getUserLoggedInObs()
}

The in your View you can add

<div *ngIf="userLoggedInObs | async">
  User is logged in
</div>
<div *ngIf="!(userLoggedInObs | async)">
  User isn't logged in
</div>

When you call the service it will broadcast to all components currently subscribed to it, which will then live update.

like image 183
Daniel Swiegers Avatar answered Oct 11 '22 22:10

Daniel Swiegers