簡體   English   中英

RxJS-.map()和.subscribe()問題

[英]RxJS - issue with .map() and .subscribe()

angular2使用.subscribe() .map().subscribe()RxJS angular2 請在以下代碼中找到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.jsSystemJS v0.19.6typescript 1.7.3Rx.jsangular2.dev.jshttp.dev.js

.map().subscribe()在這里可能是什么問題?

這看起來與RxJS無關。您的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"
  }
]

嘗試解析name ,JSON解析器會中斷,因此錯誤中的Unexpected token n會中斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM