[英]SyntaxError: Unexpected token u in JSON at position 0 in Angular2 when try to store in local storage
I have a json response like this. 我有一个像这样的json响应。
{
"response": {
"data": {
"name": "ABC",
"Id": "1234",
"address": "adthhyrr"
}
}
}
In service.ts I am doing a request like this to get the response data. 在service.ts中,我正在执行这样的请求以获取响应数据。
public getResponseData() : Promise<any> {
if(typeof(this.login_data) === "undefined") {
return this.http.get('assets/response.json')
.toPromise().then(res => {
this.login_data = res.json().response.data;
return this.login_data;
}).catch(this.handleError);
} else {
return Promise.resolve(this.login_data);
}
}
And I am storing the login_data in localstorage like this 我像这样将login_data存储在localstorage中
getAllData() {
if (localStorage.getItem('login_data') === null || localStorage.getItem('login_data') === undefined) {
localStorage.setItem('login_data', JSON.stringify(this.login_data));
return this.login_data;
}
else {
var login_data = JSON.parse(localStorage.getItem('login_data'));
return login_data;
}
}
And in component.ts class I am getting data like this 在component.ts类中,我正在获取这样的数据
this.logindata = this.myservice.getAllData();
But while doing this I am getting this error. 但是在执行此操作时,我收到此错误。 SyntaxError: Unexpected token u in JSON at position 0 .
SyntaxError:JSON中位置0处的意外令牌u 。
But if i am not storing in localstorage then i am doing like this in service. 但是,如果我不存储在本地存储中,那么我将在服务中这样做。
public getAllData(): any { public getAllData():任何{
return this.login_data;
} }
And in component.ts file i am getting data by calling this method. 在component.ts文件中,我通过调用此方法获取数据。
this.logindata = this.myservice.getAllData();
And here it is working fine.But when i am trying to store data into localstorage and want to fetch from local storage i am getting this error. 在这里它工作正常。但是当我尝试将数据存储到localstorage并想从本地存储中获取时,我遇到了这个错误。 SyntaxError: Unexpected token u in JSON at position 0
SyntaxError:JSON中位置0处的意外令牌u
Can anyone please tell me where exactly i am doing wrong. 谁能告诉我我到底在哪里做错。
The error SyntaxError: Unexpected token u in JSON at position 0
says that you are trying to parse an object to object which is not possible . 错误
SyntaxError: Unexpected token u in JSON at position 0
表示您试图将对象解析为不可能的对象 。
So, while retrieving from localStorage
check the type and parse if it is not an object
因此,从
localStorage
检索时,请检查类型并解析它是否不是object
Also change the if condition to, if ( !(localStorage.getItem('login_data'))) {
还要将if条件更改为if
if ( !(localStorage.getItem('login_data'))) {
getAllData() {
var data = localStorage.getItem('login_data');
if (!data) {
localStorage.setItem('login_data', JSON.stringify(this.login_data));
return this.login_data;
} else {
var login_data;
if(typeof data == 'object')
{
login_data = data;
}else{
login_data = JSON.parse(data);
}
return login_data;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.