web-dev-qa-db-fra.com

SyntaxError jeton inattendu u dans JSON sur la position 0 Angular2

J'ai essayé de créer un serveur avec des données factices.

Voici ma configuration System.js (puisque j'ai un routage légèrement différent, cela semblait bien fonctionner jusqu'à présent)

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));

voici mon 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');
  }
}

cependant, si je change le journal de la console en console.log (data), il retourne indéfini.

J'ai regardé partout, mais aucune des réponses n'a résolu mon cas. Cela pourrait être un problème avec le système js, mais comme tout le reste semble fonctionner correctement, je ne trouve vraiment pas comment résoudre ce problème.

Voici la réponse dans la console:

réponse de la console:

enter image description here

7
Astrid Karsten

JSON.stringify(undefined) entraîne un JSON invalide, c'est pourquoi JSON.parse(JSON.stringify(data)) lance.

Vous pouvez changer votre code en

JSON.parse(JSON.stringify(data || null ))
20