Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError unexpected token u in JSON on position 0 Angular2

I tried to make a server with some dummy data.

Here is my System.js Config (since I have a slightly different routing, this seemed to work fine up till now)

System.config({

            // baseURL to node_modules
            baseURL: '/plugins/dashboard/assets/@@version@@/node_modules',
            defaultJSExtensions: true
        });
        System.import('/plugins/dashboard/assets/@@version@@/app/main')
                .then(null, console.error.bind(console));

here is my service:

import {Injectable}     from 'angular2/core';
import {Http, Response} from 'angular2/http';
//import {Observable }     from 'rxjs/Observable';
import {Observable} from 'rxjs/Rx';

import {newsLetter} from "../objects/newsLetter";


@Injectable()

export class newsLetterService {
constructor (private http: Http) {}

//Need to change this URL
private _myNewsLetterUrl = "http://epub-core.dev.prisma-it.com:8888/plugins/dashboard/assets/@@version@@/app/data/newsLetter.json";  // URL to web api

getNewsLetter () {
    console.log(this._myNewsLetterUrl);
    console.log(this.http.get(this._myNewsLetterUrl));
    return this.http.get(this._myNewsLetterUrl)
        .map(res => <newsLetter[]> res.json().data)
        // eyeball objects as json objects in the console | mapping purposes
        .do(data => console.log(JSON.parse(JSON.stringify(data))))
            .catch(this.handleError);

  }

  private handleError (error: Response) {
    // in a real world app, we may send the error to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

however, if I change the console log to console.log(data) it is returning undefined.

I looked everywhere, but none of the answers solved my case. It might be a problem with system js, but since everything else seems to work fine, I really cannot find how to fix this.

This is the response in the console:

console response:

enter image description here

like image 713
Astrid Karsten Avatar asked May 09 '16 11:05

Astrid Karsten


Video Answer


1 Answers

JSON.stringify(undefined) results in invalid JSON, this is why JSON.parse(JSON.stringify(data)) throws.

You might change your code to

JSON.parse(JSON.stringify(data || null ))
like image 127
Günter Zöchbauer Avatar answered Nov 15 '22 21:11

Günter Zöchbauer