Angular:错误 SyntaxError:JSON 中位置 0 处出现意外标记 <

Ana*_*nas 5 json http observable angular

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

应用程序组件.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);
      }
    }
Run Code Online (Sandbox Code Playgroud)

汽车服务.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

汽车-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"
    }
]
Run Code Online (Sandbox Code Playgroud)

先感谢您。

AJT*_*T82 5

除了使用注释中建议的正确路径之外,您的问题是您试图从不存在的内容中提取数据。看一下你的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 || []; 
}
Run Code Online (Sandbox Code Playgroud)

这应该可以完成,并更正 JSON 文件的路径。