0
votes

I am new to Angular. I am trying to do login/logout operations. Login and logout were working succeessfully but when the user clicks the logout button, user component does not change and login button does not come again. Is it the that the problem about login and account operations are in different components and these two component becoming together in app-nav-user-layout component.

nav-user.component.ts

@Component({
  selector: 'app-nav-user',
  templateUrl: './nav-user.component.html',
  styleUrls: ['./nav-user.component.css']
})
export class NavUserComponent implements OnInit {
  name: string = "";
  roles: any = [];
  token: any;
  welcomeMessage: string;
  constructor(
    private jwtHelper: JwtHelperService,
    private localStorageService: LocalStorageService,
    private authService: AuthService
  ) { }

  ngOnInit(): void {
    this.userDetailFromToken();
    this.welcomeMessage = GlobalConstants.Messages.welcomeMessage;
  }

  userDetailFromToken() {
    this.token = this.localStorageService.get("token");
    let decodedToken = this.jwtHelper.decodeToken(this.token);
    let name = decodedToken['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'];
    this.name = name.split(' ')[0];
    this.roles = decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'];  
  }

  logOut(){
    this.authService.logout();
  }
}

Html file of nav-user component

<span>
    {{welcomeMessage}} {{name}}
</span>
<button class="btn btn-secondary btn-sm dropdown-toggle shadow-none ms-2 " type="button" data-bs-toggle="dropdown"
    aria-expanded="false">
    <fa-icon [icon]="['fas', 'user-cog']"></fa-icon> Panel
</button>
<ul class="dropdown-menu p-0">
    <li><a class="dropdown-item" routerLink="/user/settings">Profile Settings</a></li>
    <div *ngIf="roleCheck(['admin', 'yazar'])">
        <li>
            <hr class="dropdown-divider">
        </li>
        <h6 class="dropdown-header">Administration</h6>
        <li><a class="dropdown-item" routerLink="/add/car">Add Car</a></li>
        <li><a class="dropdown-item" routerLink="/add/color">Add Color</a></li>
        <li><a class="dropdown-item" routerLink="/add/brand">Add Brand</a></li>
    </div>
</ul>

<button class="btn btn-danger btn-sm ms-2 shadow-none" type="button" (click)="logOut()">
    <fa-icon [icon]="['fas', 'sign-out-alt']"></fa-icon>
</button>

auth.service.ts

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(
    private httpClient: HttpClient,
    private localStorageService: LocalStorageService,
    private router: Router
  ) { }

  login(loginModel: LoginModel): Observable<SingleResponseModel<TokenModel>>{
    return this.httpClient.post<SingleResponseModel<TokenModel>>(GlobalConstants.apiUrl + "auth/login", loginModel);
  }

  register(registerModel: RegisterModel) : Observable<ResponseModel>{
    return this.httpClient.post<ResponseModel>(GlobalConstants.apiUrl + "auth/register", registerModel);
  }

  isAuthenticated(): boolean{
    return this.localStorageService.checkExistsOrNot("token");
  }

  logout(){
    this.localStorageService.clean();
    this.router.navigateByUrl('/');
  }

}

nav-login.component.ts is empty. Because I just use it for html. Html file includes login and register buttons and these are redirect to /login & /register pages

app-header-account-area.ts

@Component({
  selector: 'app-app-header-account-area',
  templateUrl: './app-header-account-area.component.html',
  styleUrls: ['./app-header-account-area.component.css']
})
export class AppHeaderAccountAreaComponent implements OnInit {

  isLoggedIn: boolean;
  constructor(
    private authService: AuthService
  ) { }

  ngOnInit(): void {
    this.isLoggedIn = this.authService.isAuthenticated();
  }
}

html of this component

<app-nav-login *ngIf="isLoggedIn==false"></app-nav-login>
<app-nav-user *ngIf="isLoggedIn==true"></app-nav-user>

How can I change view when the user press on the logout button? I can't find anything or didn't understand those solutions about communication of 2 components.

1
If possible then provide a stackblitz demo - Prashant Pimpale
@PrashantPimpale sorry, I am working on localhost. I don't have an api running on the web. - IDKAnythingAboutMe
Then it's bit hard to guess, if possible then provide a demo without API call - Prashant Pimpale
@PrashantPimpale all program work with that api. But I found a solution. I merged login and user components and when the user press on the logout button, ngOnInit() working. So, the component will refresh with this way. Thank you for your attention. - IDKAnythingAboutMe
I was gonna suggest routing and route guards that kick you back to the login page - iamaword

1 Answers

0
votes

Not sure how relevant this is but if you wanted to refresh a component by refreshing the route, here is one way to do it.

  onRefresh() {
    this.router.routeReuseStrategy.shouldReuseRoute = function () { return false }
    const currentUrl = this.router.url + '?'
    return this.router.navigateByUrl(currentUrl).then(() => {
      this.router.navigated = false
      this.router.navigate([this.router.url])
    })
  }