【发布时间】:2019-09-29 05:39:01
【问题描述】:
我需要我的登录用户,并且即使在刷新后也能继续获取他,我将他的值放入本地存储中。当我使用 JSON.stringify() 时,它会将正确的值放在本地存储中,但在键名前面带有 _,我不知道为什么(我将我的私有属性命名为 _id,例如,但我写了 getter,我认为应该再次正常命名它们吗?)。因为不行,所以自己写了toJSON方法:
toJSON(): any {
return {
id: this._id,
firstName: this._firstName,
lastName: this._lastName,
email: this._email,
phoneNumber: this._phone,
country: this._country,
comments: this._comments.map(c => c.toJSON)
};
但是当我调用它时,它会将 [object Object] 放入本地存储中,我不知道为什么会这样做。
我基本上需要让 JSON.stringify 将我的属性放在 localStorage 中,或者我需要修复我的 toJson。
用户模型:
import { Comment } from '../image/comment.model';
export class User {
constructor(
private _id: number,
private _firstName: string,
private _lastName: string,
private _email: string,
private _phone: string,
private _country: string,
private _comments: Comment[]
) {}
get id(): number {
return this._id;
}
get firstName(): string {
return this._firstName;
}
get lastName(): string {
return this._lastName;
}
get email(): string {
return this._email;
}
get phone(): string {
return this._phone;
}
get country(): string {
return this._country;
}
get comments(): Comment[] {
return this._comments;
}
static fromJSON(json: any): User {
return new User(
json.id,
json.firstName,
json.lastName,
json.email,
json.phoneNumber,
json.country,
json.comments
);
}
toJSON(): any {
return {
id: this._id,
firstName: this._firstName,
lastName: this._lastName,
email: this._email,
phoneNumber: this._phone,
country: this._country,
comments: this._comments.map(c => c.toJSON)
};
}
}
认证服务
this.getUser(email).subscribe(usr => { //this gets my user via its email from the backend
localStorage.setItem('visitor', usr.toJSON());
this._loggedInUser$.next(usr);
});
this._loggedInUser$ = new BehaviorSubject<User>(
localStorage.getItem('visitor')
? User.fromJSON(localStorage.getItem('visitor'))
: null
);
get loggedInUser$(): BehaviorSubject<User> {
return this._loggedInUser$;
}
评论
export class Comment {
private _id: number;
constructor(
private _author: string,
private _content: string,
private _date: Date,
private _imageId: number,
private _visitorId: number
) {}
get id(): number {
return this._id;
}
set id(value: number) {
this._id = value;
}
get author(): string {
return this._author;
}
get content() {
return this._content;
}
get date(): Date {
return this._date;
}
get imageId(): number {
return this._imageId;
}
get visitorId(): number {
return this._visitorId;
}
static fromJSON(json: any): Comment {
let comment = new Comment(
json.author,
json.content,
json.date,
json.myImageId,
json.visitorId
);
comment.id = json.id;
return comment;
}
toJSON(): any {
return {
id: this._id,
author: this._author,
content: this._content,
date: this._date,
myImageId: this._imageId,
visitorId: this._visitorId
};
}
}
如果需要更多代码,请告诉我!
【问题讨论】:
-
您似乎在编写 Typescript,就像在编写 Java 一样。不需要所有的类私有成员变量和 getter。在对对象进行字符串化/解析时,您正在重新发明轮子。您的
toJSON()函数返回对象,而不是 JSON,这似乎是您在这篇文章中的问题。您是否打算在所有类中创建这些函数?你真的想要吗? -
@R.Richards 我们知道这不是学校的最佳实践(私有属性和公共 getter)
标签: json angular typescript local-storage