Angular 类型为'的参数;字符串| null';不可分配给类型为';字符串';。类型';空';不可分配给类型';字符串';

Angular 类型为'的参数;字符串| null';不可分配给类型为';字符串';。类型';空';不可分配给类型';字符串';,angular,typescript,Angular,Typescript,我有一个dotnetcore 20和angular4项目,我正在尝试创建一个userService并将用户带到我的主页组件。后端工作正常,但服务不正常。问题出在本地存储上。我收到的错误消息是: “string | null”类型的参数不能分配给“string”类型的参数。 类型“null”不可分配给类型“string” 还有我的用户服务 import { User } from './../models/users'; import { AppConfig } from './../../app

我有一个dotnetcore 20和angular4项目,我正在尝试创建一个userService并将用户带到我的主页组件。后端工作正常,但服务不正常。问题出在本地存储上。我收到的错误消息是:

“string | null”类型的参数不能分配给“string”类型的参数。 类型“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 });
    }
}
我的家是

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'))上

正如错误所说,
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();
另见。如果您确信
localStorage.getItem()
调用永远不会返回
null
,则可以使用非null断言运算符告诉typescript您知道自己在做什么:

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

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

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

通过使用上述解决方案,我为使这个问题在我的案例中起作用进行了很多努力,但没有一个成功。 对我有效的是:

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

我必须将变量强制转换为string | any,然后在解析它之前检查变量是否为null或未定义

是否必须以字符串结尾?说它可以为空?我不确定您在哪里指定字符串类型。在这种情况下,我甚至不知道哪一个是null,哪一个是字符串。错误发生在本地存储上。它只是无法从localStorage获取用户。Ref:谢谢,我更新了我的答案以引用您的答案,以防人们在页面上看得不够远。只有当您确信该值永远不会返回null时,您才能使用非null断言运算符告诉typescript您知道自己在做什么Hi!谢谢你的回答,这是有道理的,但我在这里尝试过,但仍然遇到同样的错误,介意看一看吗?:)事实上,很抱歉,您发布的第一个示例有效,第二个没有:)
this.currentUser=JSON.parse(localStorage.getItem('currentUser')| |{})