如何解决此' string | null'无法分配给类型的参数' string' .type' null'不能分配给类型' String'

发布于 2025-01-24 15:28:13 字数 3440 浏览 4 评论 0原文

//我在网上购物我被此登录服务所困扰

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 {

/* 类型'字符串|的参数| null'不能分配给类型“字符串”的参数。类型'null'不能分配给类型'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;

问题类型'string | null'不能分配给类型“字符串”的参数。类型'null'不能分配给类型'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);
        }

问题类型'string | null'不能分配给类型“字符串”的参数。键入“ null”不可分配给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]

//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]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肩上的翅膀 2025-01-31 15:28:13

您不一定会从localstorage.getItem(“ userId”)中返回可以解析的任何内容。

如果UserID只是一个字符串,它似乎是

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

一个字符串 。

,则可以将其返回而无需json。在这种情况下,您可以进行以下操作

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

您似乎在其他示例中遇到了相同的问题,但是您可以以相同的方式修复它们,除非

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

应该是

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

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文