[英]Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'
I have a dotnetcore 20 and angular4 project that I am trying to create a userService and get the user to my home component.我有一个 dotnetcore 20 和 angular4 项目,我正在尝试创建一个 userService 并让用户访问我的主组件。 The backend works just fine but the service doesn't.
后端工作得很好,但服务却不行。 The problem is on localStorage .
问题出在localStorage上。 The error message that I have is :
我收到的错误消息是:
Argument of type 'string |
'string | 类型的参数null' is not assignable to parameter of type 'string'.
null' 不能分配给“字符串”类型的参数。 Type 'null' is not assignable to type 'string'.
类型“null”不能分配给类型“string”。
And my 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 });
}
}
And my home.component.ts is而我的 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; });
}
The error is on JSON.parse(localStorage.getItem('currentUser'));
错误在
JSON.parse(localStorage.getItem('currentUser'));
As the error says, localStorage.getItem()
can return either a string or null
. 如错误所示,
localStorage.getItem()
可以返回字符串或null
。 JSON.parse()
requires a string, so you should test the result of localStorage.getItem()
before you try to use it. JSON.parse()
需要一个字符串,因此在尝试使用它之前,应该测试localStorage.getItem()
的结果。
For example: 例如:
this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
or perhaps: 也许:
const userJson = localStorage.getItem('currentUser');
this.currentUser = userJson !== null ? JSON.parse(userJson) : new User();
See also the answer from Willem De Nys . 另见Willem De Nys的答案 。 If you are confident that the
localStorage.getItem()
call can never return null
you can use the non-null assertion operator to tell typescript that you know what you are doing: 如果您确信
localStorage.getItem()
调用永远不会返回null
,则可以使用非null断言运算符告诉typescript您知道自己在做什么:
this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
接受的答案是正确的,只是想添加一个更新更短的答案。
this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
The non-null assertion operator worked for me very well:非空断言运算符对我很有效:
(1). (1). in my case
就我而言
this.currentUserSource.next(null!)
(2). (2). in your case
在你的情况下
this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
Type 'string |输入'字符串| null' is not assignable to type 'string'.
null' 不可分配给类型 'string'。 Type 'null' is not assignable to type 'string'.
类型 'null' 不能分配给类型 'string'。
export class TodoComponent implements OnInit {
loacalitems!: string;
todos!: Todo[];
constructor() {
this.loacalitems = localStorage.getItem("todos");
}
because localStorage.getItem()
return string or null
solve this problem any variable this type error is define variable因为
localStorage.getItem()
返回string or null
解决这个问题任何变量这种类型的错误是定义变量
localitems!: string | null;
this variable holds to type values string or null.此变量用于类型值 string 或 null。 then write logic
然后写逻辑
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 = []
}
Any ideas for this:对此的任何想法:
export const useStateWithLocalStorage = (defaultValue: string[], key: string) => {
const [value, setValue] = useState(() => {
const storedValues = localStorage.getItem(key);
return storedValues !== null ? JSON.parse(storedValues) : defaultValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
};
I have struggled a lot making this issue worked in my case by using the above solution but none of them succeeded.通过使用上述解决方案,我一直在努力使这个问题在我的案例中起作用,但没有一个成功。 What workied for me is:
对我有用的是:
const serializableState: string | any = localStorage.getItem('globalState');
return serializableState !== null || serializableState === undefined ? JSON.parse(serializableState) : undefined;
I had to cast my variable to string |我不得不将我的变量转换为字符串 | any and then checked if the variable is null or undefined before parsing it
any 然后在解析之前检查变量是否为空或未定义
localsetItem: string | null;
constructor() {
this.localsetItem=localStorage.getItem("todos")
if(this.localsetItem == null)
{
this.todos = [];
}
else
{
this.todos=JSON.parse(this.localsetItem);
}
}
尝试这个
private userSubject$ = new BehaviorSubject<User | unknown>(null);
我解决了它如下
router.navigateByUrl(returnUrl!);
Using Angular or TS:-使用 Angular 或 TS:-
JSON.parse(localStorage.getItem('user') as string);
or或者
JSON.parse(localStorage.getItem('user') as any);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.