Search code examples
javascriptnode.jsangulartypescriptmean-stack

how to Solve this 'string | null' is not assignable to parameter of type 'string'.Type 'null' is not assignable to type 'string'


//I doing This Online Shopping i got stuck with this login service

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
import { Router } from '@angular/router';
import { EmployeeService } from '../employee.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  login = true;
  attemptsLeft = 3;
  userID!:number;
  isAdmin:boolean = false;
  isLoggedIn:boolean = false;
  constructor(public _service:UserService, public userSer:UserService, public route: Router, public empSer: EmployeeService) { }

  ngOnInit(): void {

/* Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'

this.userID = JSON.parse((localStorage.getItem("userId")));//problem here 

    if(this.userID.toString() != ""){
      this.isLoggedIn = true;
    }
    let employee = this.empSer.getEmployee(this.userID).subscribe(employee =>{
      this.isAdmin = employee[0].isAdmin;
    });
    //if user -> send to user
    if(this.isLoggedIn){
      this.route.navigate(['/home-page']);
    }
  }
  checkLogin(loginRef:any){
    this._service.attemptLogin(loginRef).
    subscribe((id: string)=>{
      console.log(id);
      if(id == ""){
        console.log("incorrect");
        this.login = false;

problem here Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'

    let incorrectAttempts = 
 JSON.parse(sessionStorage.getItem("incorrectAttempts"));
        console.log(incorrectAttempts);
        if(incorrectAttempts == null){
          incorrectAttempts = 0;
        }
        incorrectAttempts++;
        this.attemptsLeft --;

        if(incorrectAttempts > 2){
          this.userSer.lockUser(loginRef);
        }

problem here Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'

    sessionStorage.setItem("incorrectAttempts", `JSON.stringify(incorrectAttempts));`
      }
      else{
        localStorage.setItem("userId",JSON.stringify(id));
        sessionStorage.setItem("incorrectAttempts","0");
        this.route.navigate(['/']);
      }
    },(error: any)=>console.log(error));
    
  }
}
//user Controller  this is backend service for login 
let login = (req, res) => {
    let email = req.body.emailId;
    let password = req.body.password;
    UserModel.findOne({emailId:email},(err,user) => {
        console.log("looking for user");
        try{
            if(user.password != password){
                res.send(null);
                return;
            }
        }catch(err){
            console.log(err);
        }

        try{
            res.send(user._id.toString());
            return;
        }catch(err){}
    })

    EmployeeModel.findOne({email:email},(err,employee) => {
        console.log("looking for employee");
        console.log(employee);
        try{
            if(employee.password != password){
                res.send(null);
                return;
            }
        }catch(err){
            return;
        }
        res.send(employee._id.toString());
    })
}
//server.js login 
baseURL = "http://localhost:8080/user"
attemptLogin(loginRef:any):any{
  return this._http.post(`${this.baseURL}/login`,loginRef,{responseType:"text"})
}
please help me ! Pictures [This is the Error Picture][1]

Solution

  • You aren't necessarily returning anything from localStorage.getItem("userId") that can be JSON parsed.

    If userID is just a string, which it seems to be, you can just return it without JSON.parsing it first

    this.userID = localStorage.getItem("userId"));//problem here 
    this.isLoggedIn = this.userID != "";
    

    if you are storing userID as an object, which is implied by how you are stringfifying it in your example, then you might not have set anything to parse

    in which case you can do the following.

    let idString: string = localStorage.getItem("userId");
    this.userID = idString ? JSON.parse(idString) : null; //problem was here
    this.loggIn = this.userID != null;
    

    You seem to be encountering the same issue in the other examples, but you can fix them the same way, except for this one

    sessionStorage.setItem("incorrectAttempts", `JSON.stringify(incorrectAttempts));`
    

    which should be

     sessionStorage.setItem("incorrectAttempts", JSON.stringify(incorrectAttempts));