RxJS - .map() 和 .subscribe() 的问题

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

angular2 中使用 RxJS.map().subscribe() 时出现错误。请在下面找到 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)
                      );

    }

}

此处 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'
  }
]

错误如下:

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)

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

.map().subscribe() 可能是什么问题?

这看起来与 RxJS 无关。您的 JSON 格式错误。尝试在 prop 名称和值周围添加双引号:

[
  {
    "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 解析器在尝试解析 name 时中断,因此出现 Unexpected token n 错误。