gpt4 book ai didi

angular - 'string | null' 类型的参数不可分配给 'string' 类型的参数。类型 'null' 不可分配给类型 'string'

转载 作者:太空狗 更新时间:2023-10-29 16:54:41 24 4
gpt4 key购买 nike

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

Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type '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'));

最佳答案

如错误所述,localStorage.getItem() 可以返回字符串或 nullJSON.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')!);

关于angular - 'string | null' 类型的参数不可分配给 'string' 类型的参数。类型 'null' 不可分配给类型 'string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com