为什么我的JSON没有加载到Angular 2中

时间:2016-04-25 11:27:23

标签: json angular observable

我正在尝试将一些JSON数据加载到Angular 2组件中,但是我收到了一个错误的'意外令牌:'它似乎不明白我的json数据是什么。

我试图完成这个简单的'任务多次但我还是无法这样做,所以我希望这次可以在社区帮助下到达某个地方......

这是我的代码:

的index.html

<!DOCTYPE html>
<html>
  <head>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <title>Angular 2 QuickStart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <link rel="stylesheet" href="style.css">

    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>   

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/http.dev.js"></script>
    <script src="node_modules/angular2/bundles/router.dev.js"></script>

    <!-- 2. Configure SystemJS -->
     <script>
      System.config({
        transpiler: 'typescript', 
        typescriptOptions: { emitDecoratorMetadata: true }, 
        packages: {        
          app: { // must match your folder name
                format: 'register',
                defaultExtension: 'js'
            }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

main.ts

import {bootstrap}              from 'angular2/platform/browser';
import {Http,  HTTP_PROVIDERS}  from 'angular2/http';
import {AppComponent}           from './app.component';
import { PeopleService }        from './people.service';
import 'rxjs/Rx';

bootstrap(AppComponent, [HTTP_PROVIDERS,PeopleService]);

app.component.ts

import {Component}      from 'angular2/core';
import {ListComponent}  from './list.component';


@Component({
    selector: 'my-app',
    directives : [ListComponent],
    template: '<h1>{{applicationTitle}}</h1><my-list></my-list>'
})

list.component.ts

import {Component}          from 'angular2/core';
import {HTTP_PROVIDERS}     from 'angular2/http';
import {PeopleService}      from './people.service'
import {Person}             from './person'


@Component({
    selector: 'my-list',
    providers:  
    [
        HTTP_PROVIDERS,
        PeopleService,
    ],
    template: `
            <h2>This is the List component</h2>
            <div *ngFor="#person of people">
                <h2>{{person.name}}</h2>
                <h3>{{person.age}}</h3>
            </div>
    `
})


export class ListComponent 
{
    people : Array<Person>

    constructor(private _personService:PeopleService)
    {
        _personService.getPeople()
                      .subscribe(response => this.people = response);         
    }

}

people.service.ts

import {Injectable}     from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Person}         from './person';
import {Observable}     from 'rxjs/Observable';

@Injectable()
export class PeopleService {

  constructor(private http: Http) { }

  private dataURL = './app/people.json';  

  getPeople(): Observable<Person[]> {
    return this.http.get(this.dataURL)
                    .map(this.onSuccess)
                    .catch (this.onFail);
  }


  private onSuccess(res: Response) {
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    let     body = res.json();
    return  body.data || { };

  }


  private onFail(error: any) {
    let errMsg = error.message || 'Server error';
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

person.ts

export class Person()
{
    age: number;
   name: string;
}

people.json

"people":[
    { age: 40, name: "Jordan Houston" },
    { age: 38, name: "Robert Eastham" },
    { age: 23, name: "Josh Beh" },
    { age: 23, name: "Joseph Canina" },
    { age: 24, name: "Alexandra Wilkins" },
    { age: 22, name: "Kiersten Costanzo" },
    { age: 23, name: "Ku Sherwood" },
    { age: 25, name: "Arta Halili" },
    { age: 24, name: "Patrick Cooney" },
    { age: 23, name: "Z.A. Perr" },
    { age: 18, name: "Tyler Mulligan" },
    { age: 26, name: "Dennis Dempsey" },
    { age: 32, name: "Francis Yeager" },
    { age: 23, name: "Phil Belardi" }
]

实际错误如下:

people.service.ts:32 Unexpected token :System.register.context_1.execute.PeopleService.onFail @ people.service.ts:32CatchSubscriber.error @ Rx.js:3239MapSubscriber._next @ Rx.js:5041Subscriber.next @ Rx.js:10667onLoad @ http.dev.js:660ZoneDelegate.invokeTask @ angular2-polyfills.js:365NgZoneImpl.inner.inner.fork.onInvokeTask @ angular2.dev.js:2103ZoneDelegate.invokeTask @ angular2-polyfills.js:364Zone.runTask @ angular2-polyfills.js:263ZoneTask.invoke @ angular2-polyfills.js:431
angular2.dev.js:23887 EXCEPTION: Unexpected token :

我对错误的格式化道歉

将json格式更改为以下

{
    "people":[
        { "age": 40, "name": "Jordan Houston" },
        { "age": 38, "name": "Robert Eastham" },
        { "age": 23, "name": "Josh Beh" },
        { "age": 23, "name": "Joseph Canina" },
        { "age": 24, "name": "Alexandra Wilkins" },
        { "age": 22, "name": "Kiersten Costanzo" },
        { "age": 23, "name": "Ku Sherwood" },
        { "age": 25, "name": "Arta Halili" },
        { "age": 24, "name": "Patrick Cooney" },
        { "age": 23, "name": "Z.A. Perr" },
        { "age": 18, "name": "Tyler Mulligan" },
        { "age": 26, "name": "Dennis Dempsey" },
        { "age": 32, "name": "Francis Ye"age"r" },
        { "age": 23, "name": "Phil Belardi" }
    ]
}

将错误更改为:

angular2.dev.js:23877 EXCEPTION:意外的令牌a

3 个答案:

答案 0 :(得分:2)

您的JSON内容格式不正确。你应该用这个:

{
  "people":[
    { "age": 40, "name": "Jordan Houston" },
    (...)
  ]
}

不要忘记属性名称周围的"

答案 1 :(得分:0)

您的PeopleService正在返回body.data,但是在您的json文件中没有提供该属性。尝试将所有内容包装到json文件中的数据属性中,或者更改PeopleService,使其不再返回body.data,而只返回body(或者在您的情况下为body.people)。

答案 2 :(得分:0)

另请注意Francis Yeager的错误报价。