【问题标题】:Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string''string | 类型的参数null' 不能分配给“字符串”类型的参数。 “null”类型不能分配给“string”类型
【发布时间】:2018-04-05 12:21:58
【问题描述】:

我有一个 dotnetcore 20 和 angular4 项目,我正在尝试创建一个 userService 并让用户访问我的主组件。后端工作得很好,但服务却不行。问题出在 localStorage 上。我收到的错误消息是:

'string | 类型的参数null' 不能分配给“字符串”类型的参数。 类型 'null' 不能分配给类型 'string'。

还有我的用户服务

import { User } from './../models/users';
import { AppConfig } from './../../app.config';
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';



@Injectable()
export class UserService {
constructor(private http: Http, private config: AppConfig) { }

getAll() {
    return this.http.get(this.config.apiUrl + '/users', this.jwt()).map((response: Response) => response.json());
}

getById(_id: string) {
    return this.http.get(this.config.apiUrl + '/users/' + _id, this.jwt()).map((response: Response) => response.json());
}

create(user: User) {
    return this.http.post(this.config.apiUrl + '/users/register', user, this.jwt());
}

update(user: User) {
    return this.http.put(this.config.apiUrl + '/users/' + user.id, user, this.jwt());
}

delete(_id: string) {
    return this.http.delete(this.config.apiUrl + '/users/' + _id, this.jwt());
}

// private helper methods

private jwt() {
    // create authorization header with jwt token
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (currentUser && currentUser.token) {
        let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
        return new RequestOptions({ headers: headers });
    }
}

而我的 home.component.ts 是

import { UserService } from './../services/user.service';
import { User } from './../models/users';
import { Component, OnInit } from '@angular/core';

@Component({
moduleId: module.id,
templateUrl: 'home.component.html'
})

export class HomeComponent implements OnInit {
currentUser: User;
users: User[] = [];

constructor(private userService: UserService) {
   this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}

ngOnInit() {
   this.loadAllUsers();
}

deleteUser(_id: string) {
   this.userService.delete(_id).subscribe(() => { this.loadAllUsers() });
}

private loadAllUsers() {
   this.userService.getAll().subscribe(users => { this.users = users; });
}

错误在JSON.parse(localStorage.getItem('currentUser'));

【问题讨论】:

  • 您不必以 结束类型吗?说它可以为空?我不确定你在哪里指定字符串类型。
  • 在这种情况下,我什至不知道哪个是null,哪个是字符串。错误出现在 localStorage 上。它只是没有从 localStorage 获取用户。

标签: angular typescript


【解决方案1】:

正如错误所说,localStorage.getItem() 可以返回字符串或null。 JSON.parse() 需要一个字符串,所以你应该在尝试使用之前测试localStorage.getItem() 的结果。

例如:

this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');

或许:

const userJson = localStorage.getItem('currentUser');
this.currentUser = userJson !== null ? JSON.parse(userJson) : new User();

另请参阅answer from Willem De Nys。如果您确信 localStorage.getItem() 调用永远不会返回 null 您可以使用非空断言运算符告诉 typescript 您知道自己在做什么:

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);

【讨论】:

  • 嗨!感谢您的回答,这是有道理的,但我在这里尝试过,但仍然遇到同样的错误,介意看看吗? :) stackoverflow.com/questions/54715260/…
  • 其实,对不起,你发布的第一个例子有效,第二个没有:) this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
【解决方案2】:

接受的答案是正确的,只是想添加一个更新更短的答案。

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);

【讨论】:

  • 谢谢,我更新了我的答案以参考你的答案,以防人们在页面下方看的不够远。
  • 仅当您确信该值永远不会返回 null 时,您可以使用非 null 断言运算符告诉 typescript 您知道自己在做什么
【解决方案3】:

非空断言运算符非常适合我:

(1)。就我而言

this.currentUserSource.next(null!)

(2)。在你的情况下

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);

【讨论】:

    【解决方案4】:

    键入'字符串 | null' 不可分配给类型 'string'。类型 'null' 不能分配给类型 'string'。

    export class TodoComponent implements OnInit {
      
      loacalitems!: string;
      todos!: Todo[];
    
      constructor() {
        this.loacalitems = localStorage.getItem("todos");
    }
    

    因为localStorage.getItem() return string or null 解决这个问题 any variable 这种类型的错误是定义变量

    localitems!: string | null;
    

    此变量保存类型值 string 或 null。 然后写逻辑

    如果没有,则短手

    this.todos = this.localitems !== null ? JSON.parse(this.localitems) : [];
    

    如果-否则

    if(this.localitems !== null){
       // item not null code
       this.todos = JSON.parse(this.localitems)
    }else{
       // item is null code
       this.todos = []
    }
    

    【讨论】:

      【解决方案5】:

      通过使用上述解决方案,我一直在努力解决这个问题,但没有一个成功。 对我有用的是:

         const serializableState: string | any = localStorage.getItem('globalState');
          return serializableState !== null || serializableState === undefined ? JSON.parse(serializableState) : undefined;
      

      我不得不将我的变量转换为字符串 |任何,然后在解析之前检查变量是否为空或未定义

      【讨论】:

        【解决方案6】:
          localsetItem: string | null;
          constructor() { 
          this.localsetItem=localStorage.getItem("todos")
          if(this.localsetItem == null)
          {
            this.todos  = [];
          }
          else
              {
            this.todos=JSON.parse(this.localsetItem);
              }
           }
        

        【讨论】:

          【解决方案7】:

          试试这个

          private userSubject$ = new BehaviorSubject<User | unknown>(null);
          
          

          【讨论】:

            猜你喜欢
            • 2021-09-30
            • 2021-09-06
            • 1970-01-01
            • 2021-09-22
            • 2021-06-12
            • 1970-01-01
            • 2022-01-27
            • 2021-07-14
            • 2021-10-02
            相关资源
            最近更新 更多