Rahul Unnikrishnan
Rahul Unnikrishnan

Reputation: 69

calling a method in app.component.ts from another component in angular 6

I am new to angular and trying to learn it. I have a function in app.component.ts which injects a menu to app.component.html and the menu variable is dynamic based on the permission of logged in user, now I want to call this method once the user logged in how can I do it effectively

This is my app.component.ts

    @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test App';
  constructor(private authService:AuthService){}
  public userName;
  public permission;
  public jwtHelper = new JwtHelperService();
  public menuItems=[];

 setMenu(){
    if(this.authService.loggedIn()){
        const token = localStorage.getItem('token');
        const decodedToken = this.jwtHelper.decodeToken(token);
        this.userName = decodedToken.userName;
        this.hospitalName = decodedToken.hospitalName;
        this.permission = decodedToken.permission;
        if(this.permission == 'admin'){
            this.menuItems = this.adminMenuItems;
        }
        else{
            this.menuItems = this.nurseMenuItems;
        }
    }

  }

Upvotes: 1

Views: 3519

Answers (2)

user184994
user184994

Reputation: 18281

In your auth service, create an Observable that emits each time the login status changes:

import { Subject, Observable } from 'rxjs';     

private _statusChange$ = new Subject<boolean>();
private loginStatus$ = this._statusChange$.asObservable();

// Whenever the status changes:
this._statusChange$.next(newIsLoggedInValue);

Then, inside your component, change your code so it listens to that Observable, like so:

this.authService.loginStatus$.subscribe((isLoggedIn) => {
    if(isLoggedIn()){
        const token = localStorage.getItem('token');
        const decodedToken = this.jwtHelper.decodeToken(token);
        this.userName = decodedToken.userName;
        this.hospitalName = decodedToken.hospitalName;
        this.permission = decodedToken.permission;
        if(this.permission == 'admin'){
            this.menuItems = this.adminMenuItems;
        } else {
            this.menuItems = this.nurseMenuItems;
        }
    }
})

This way, it will fire each time the login status changes

Upvotes: 3

Rahul
Rahul

Reputation: 2128

Just call it in ngOnInit() method which gets triggered when your components loaded

export class AppComponent implements OnInit {
  ngOnInit() {
    this.setMenu();
    }
  }

Make sure you import - import { OnInit } from '@angular/core';

Happy coding !!

Upvotes: 0

Related Questions