2016-01-20 84 views
1

angular2使用RxJS.map().subscribe()時收到錯誤。請發現以下代碼app.component.tsRxJS - 問題與.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文件加載成功,這意味着angular2http工作正常,但我不能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.jsSystemJS v0.19.6typescript 1.7.3Rx.jsangular2.dev.jshttp.dev.js

有什麼能在這裏與.map().subscribe()的問題?

+0

什麼是錯誤? – dfsq

+0

@ dfsq-添加錯誤消息。 – Valay

+0

這看起來像一個格式不正確的JSON。嘗試jsonlint.com – Pierre

回答

2

這看起來與RxJS沒有關係。您的JSON格式不正確。試圖解析name

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

的JSON解析器斷裂,因此在錯誤的Unexpected token n:嘗試圍繞道具名稱和值加雙引號。