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

GoG*_*oGo 23 typescript .net-core asp.net-core angular

我有一个dotnetcore 20和angular4项目,我正在尝试创建一个userService并让用户访问我的home组件.后端工作正常,但服务没有.问题出在localStorage上.我的错误消息是:

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

和我的userService

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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

而我的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; });
}
Run Code Online (Sandbox Code Playgroud)

错误已开启 JSON.parse(localStorage.getItem('currentUser'));

Dun*_*can 62

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

例如:

this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
Run Code Online (Sandbox Code Playgroud)

也许:

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


小智 32

使用 Angular 或 TS:-

JSON.parse(localStorage.getItem('user') as string);
Run Code Online (Sandbox Code Playgroud)

或者

JSON.parse(localStorage.getItem('user') as any);
Run Code Online (Sandbox Code Playgroud)


Sho*_*lil 31

非空断言运算符对我来说非常有效:

(1). 就我而言

this.currentUserSource.next(null!)
Run Code Online (Sandbox Code Playgroud)

(2)。在你的情况下

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
Run Code Online (Sandbox Code Playgroud)


小智 11

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

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
Run Code Online (Sandbox Code Playgroud)

  • 参考:https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#non-null-assertion-operator (3认同)
  • 仅当您确信该值永远不会返回 null 时,您可以使用非空断言运算符来告诉打字稿您知道自己在做什么 (3认同)