Valay Desai Valay Desai - 4 months ago 46
JSON Question

RxJS - issue with .map() and .subscribe()

I am getting error when using

.map()
and
.subscribe()
of
RxJS
in
angular2
. Please find below code of
app.component.ts
.

import 'rxjs/Rx';
import {Component} from 'angular2/core';
import {Injectable, Observable} from 'angular2/core';
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

@Component({
selector: 'app-menu',
templateUrl: 'app/app-menu.html'
})

export class AppComponent {
result: Object;
error: Object;
http: Http;

constructor(http: Http) {
this.http = http;
this.loadFriendsSuccessFully();
}

loadFriendsSuccessFully(){
this.http.get('app/menu.json')
.map(res => res.json())
.subscribe(
data => this.result = data,
err => console.log('ERROR!!!'),
() => console.log('Got response from API', this.result)
);

}

}


Here
menu.json
file is loaded successfully which means
angular2
http
is working fine but I am not able to bind
json
values to template.

menu.json


[
{
name: 'Home',
icon: 'app/images/menu-item.svg'
},
{
name: 'Cell',
icon: 'app/images/menu-item.svg'
},
{
name: 'Office',
icon: 'app/images/menu-item.svg'
}
]


Below is the error:

ERROR!!! SyntaxError: Unexpected token n
at Object.parse (native)
at Function.Json.parse (http://localhost:3000/app/lib/angular2.dev.js:357:27)
at Response.json (http://localhost:3000/app/lib/http.dev.js:282:36)
at MapSubscriber.project (http://localhost:3000/app/app.component.ts!transpiled:31:58)
at MapSubscriber.tryCatcher (http://localhost:3000/node_modules/rxjs/bundles/Rx.js:7002:29)
at MapSubscriber._next (http://localhost:3000/node_modules/rxjs/bundles/Rx.js:3930:54)
at MapSubscriber.Subscriber.next (http://localhost:3000/node_modules/rxjs/bundles/Rx.js:9500:14)
at XMLHttpRequest.baseResponseOptions.response.Observable_1.Observable.onLoad (http://localhost:3000/app/lib/http.dev.js:652:30)
at Zone.run (http://localhost:3000/app/lib/angular2-polyfills.js:138:17)
at Zone.NgZone._createInnerZone.zone.fork.fork.$run [as run] (http://localhost:3000/app/lib/angular2.dev.js:5719:32)


using
es6-shim: v0.33.13
,
angular2-polyfills.js
,
SystemJS v0.19.6
,
typescript 1.7.3
,
Rx.js
,
angular2.dev.js
,
http.dev.js


What could be the issue here with
.map()
and
.subscribe()
?

Answer

This doesn't look related to RxJS.. Your JSON is malformed. Try adding double quotes around prop names and values:

[
  {
    "name": "Home",
    "icon": "app/images/menu-item.svg"
  },
  {
    "name": "Cell",
    "icon": "app/images/menu-item.svg"
  },
  {
    "name": "Office",
    "icon": "app/images/menu-item.svg"
  }
]

The JSON parser breaks when trying to parse name, therefore the Unexpected token n in the error.