1
在angular2
使用RxJS
.map()
和.subscribe()
時收到錯誤。請發現以下代碼app.component.ts
。RxJS - 問題與.MAP()和.subscribe()
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)
);
}
}
這裏menu.json
文件加載成功,這意味着angular2
http
工作正常,但我不能json
值綁定到模板。
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'
}
]
下面是錯誤:使用es6-shim: v0.33.13
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)
, angular2-polyfills.js
, SystemJS v0.19.6
, typescript 1.7.3
, Rx.js
, angular2.dev.js
, http.dev.js
有什麼能在這裏與.map()
和.subscribe()
的問題?
什麼是錯誤? – dfsq
@ dfsq-添加錯誤消息。 – Valay
這看起來像一個格式不正確的JSON。嘗試jsonlint.com – Pierre