Home > OS >  Angular: If value not found after login, logout user?
Angular: If value not found after login, logout user?

Time:09-23

I am trying to save user details in local storage so, when the user login and on the home page value i.e. username is not found user should be logout with alert and clear local storage too. but I have less clue how to do this using Angular?

checking if the username is undefined then it should be logout

on the Home page, after login, I am storing data - main.ts

import { Router } from '@angular/router';

export class MainComponent implements OnInit {
username: string | undefined;

 constructor(private router: Router)
      ngOnInit(): void {
        let date: Date = new Date();
        this.userId = localStorage.getItem('userid')
        this.username = localStorage.getItem('username')
        CheckLogin(){
        if(this.username = undefined){
               alert('please login again');
              }
         }
          }
        }

in main.html

I call my function on submit button

<input class="submit-btn" type="button" (click)="onSubmit()" (click) = "CheckLogin()" value="Submit">

if the username is undefined it should show an alert but the alert is also not showing.

I am generally mean if there is any method to check if the page does not have username value then it will show alert and logout user?

the login page is working fine and it takes user data and store in local storage.

CodePudding user response:

it should be

 if(this.username == undefined){
 alert('please login again');}

You have made an assignation not a condition

CodePudding user response:

You are not checking the condition, instead performing assignment.

Change condition

if(this.username=undefined){
       alert('please login again');}
}

And If still alert does not trigger.
Try console logging the username property. The username property should contain a value or is null.

Inside this conditional block you can call angular router navigate function, this redirects to login-page.

To do so

  1. Import Router

     import {  Router } from '@angular/router';
    
  2. Declare Router in Constructor

    private _router: Router,
    
  3. Finally under conditonal if block

    this._router.navigate(["your-page-route"]);
    
  • Related