Angular:ERROR SyntaxError:意外的令牌<在位置0的JSON中

时间:2017-05-25 00:17:06

标签: json angular http observable

您好我需要帮助我创建了一个角度服务但是当我想查看我的json文件中的数据时它向我显示了这个错误,我尝试了很多不成功的解决方案

app.component.ts

    import {Component, OnInit} from '@angular/core';
    import {Car} from './domain/car';
    import {CarService} from './service/carservice';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers: [CarService]
    })
    export class AppComponent implements OnInit {
      cars1: Car[];
      constructor(private carService: CarService) { }

      ngOnInit() {
       this.carService.getCarsSmall().subscribe(cars => this.cars1 = cars);
      }
    }

carservice.ts

@Injectable()
export class CarService {

  private jsonUrl = './cars-smalll.json';

  constructor(private http: Http) {}
    getCarsSmall(): Observable<Car[]> {
      return this.http.get(this.jsonUrl)
        .map(this.extractData)
        .catch(this.handleError);
    }

    private extractData(res: Response) {
      let body = res.json();
      return body.data || { };
    }
    private handleError (error: Response | any) {
      // In a real world app, you might use a remote logging infrastructure
      let errMsg: string;
      if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
      } else {
        errMsg = error.message ? error.message : error.toString();
      }
      console.error(errMsg);
      return Observable.throw(errMsg);
    }
}

汽车-smalll.json

[
    {
      "brand": "VW",
      "year": 2012,
      "color": "Orange",
      "vin": "dsad231ff"
    },
    {
      "brand": "Audi",
      "year": 2011,
      "color": "Black",
      "vin": "gwregre345"
    },
    {
      "brand": "Renault",
      "year": 2005,
      "color": "Gray",
      "vin": "h354htr"
    }
]

提前谢谢。

1 个答案:

答案 0 :(得分:2)

除了使用评论中建议的正确路径之外,您的问题是您正在尝试从不存在的内容中提取数据。看看你的json,它是一个阵列。但是在您的extractData - 函数中,您尝试从对象data中提取数据,这当然不会出现在您的JSON中。所以将该功能更改为:

private extractData(res: Response) {
  let body = res.json();
  // return just the response, or an empty array if there's no data
  return body || []; 
}

这应该这样做,以及更正JSON文件的路径。