B
B
Bck22018-04-13 12:31:50
Angular
Bck2, 2018-04-13 12:31:50

Unexpected token o in JSON at position 1?

There is an application where angular2-token is used. The problem is that authentication is not recorded anywhere and after refreshing the page it simply disappears. Because of this, localStorage was added, but now a syntax error appears in the console:

ERROR SyntaxError: Unexpected token o in JSON at position 1
Unhandled Promise rejection: Unexpected token o in JSON at position 1 ; Zone: <root> ; Task: Promise.then ; Value: SyntaxError: Unexpected token o in JSON at position 1

How can this be fixed?
import { Injectable } from '@angular/core';
import {Angular2TokenService} from 'angular2-token';
import { Response} from '@angular/http';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';


@Injectable()
export class AuthService {
    public token: string;
  userSignedIn$:Subject<boolean> = new Subject();

  constructor(private authService:Angular2TokenService) {
    this.userSignedIn$.next(this.authService.userSignedIn());
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.token = currentUser && currentUser.token;
  }

  logOutUser():Observable<Response>{

    return this.authService.signOut().map(
        res => {
            this.token = null;
            localStorage.removeItem('currentUser');
          this.userSignedIn$.next(false);
          return res;
        }
    );
  }

  logInUser(signInData: {email:string, password:string}):Observable<Response>{
    return this.authService.signIn(signInData).map(
        res => {
          localStorage.setItem("currentUser", signInData.toString());
          this.userSignedIn$.next(true);
          return res
        }
    );
}
  
   registerUser(signUpData:  {email:string, password:string, passwordConfirmation:string}):Observable<Response>{
    return this.authService.registerAccount(signUpData).map(
        res => {
          localStorage.setItem("currentUser", signUpData.toString());
          this.userSignedIn$.next(true);
          return res
        }
    );
  }

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Skibin, 2018-04-13
@megafax

localStorage.getItem('currentUser') what does it return for you? apparently invalid JSON check this moment

F
forspamonly2, 2018-04-13
@forspamonly2

parser zhson so swears at the line "undefined". it reacts differently to zeros and empty strings

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question