Home > Software engineering >  Angular change page depends on AuthService
Angular change page depends on AuthService

Time:09-03

I have AuthService with isAuth property and layout with navbar and i want to change buttons on it if user is authorised

part of navbar

<div *ngIf="!this.auth.isAuth; then authorizedBlock else unauthorizedBlock"></div>
    <ng-template #unauthorizedBlock>
    <ul >
      <li >
        <a  routerLinkActive="active" routerLink='login'>Login</a>
      </li>
      <li >
        <a  routerLinkActive="active" routerLink='registration'>Registration</a>
      </li>
    </ul>
    </ng-template>
    <ng-template #authorizedBlock>
      <ul >
        <li >
          <a  routerLinkActive="active" routerLink='profile'>Profile</a>
        </li>
        <li >
          <a  (click)="logout()">Logout</a>
        </li>
      </ul>
    </ng-template>

part of layout where im trying to get auth

constructor(private auth:AuthService, private  router:Router) { }
  ngOnInit(): void {
    ?????
  }

what i need to change to make it work?

this.auth.isAuth throws error that property is private

if i make local value equals to this.auth.isAuth it wont change when im login

CodePudding user response:

you can achieve this by having a get function.

in .ts file

public get isAuth(): boolean {
   return this.auth.isAuth;
}

in .html file: bit of refactoring

<ng-container *ngIf="isAuth; else unauthorizedBlock">
    <ul >
      <li >
        <a  routerLinkActive="active" routerLink='login'>Login</a>
      </li>
      <li >
        <a  routerLinkActive="active" routerLink='registration'>Registration</a>
      </li>
    </ul>
</ng-container>
  
    <ng-template #authorizedBlock>
      <ul >
        <li >
          <a  routerLinkActive="active" routerLink='profile'>Profile</a>
        </li>
        <li >
          <a  (click)="logout()">Logout</a>
        </li>
      </ul>
    </ng-template>

also, one more thing we don't need use this keyword in .html file.

  • Related