我的老板决定将Angular2应用到我们的项目中。我对这项技术很擅长。我正在尝试从url显示JSON,但结果并不像我预期的那样。 * ngFor不显示任何数据。
这是代码:
vehicle.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class VehicleService {
constructor(private http: Http){ }
getVehicle() {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}}
vehicle.component.ts
import { Component } from '@angular/core';
import { VehicleService } from './vehicle.service';
@Component({
moduleId: module.id,
selector: 'vehicle-json',
templateUrl: 'vehicle.html',
providers: [ VehicleService ]
})
export class VehicleComponent {
vehicle: Vehicle[];
constructor(private vehicleService: VehicleService){
this.vehicleService.getVehicle().subscribe(vehicle => {
/*console.log(vehicle);*/this.vehicle = vehicle;
});
}
}
interface Vehicle {
id: number;
title: string;
body: string;
}
vehicle.html
<div *ngFor="let vehicle of vehicles">
<h3>{{vehicle.title}}</h3>
<p>{{vehicle.body}}</p>
</div>
test 1-2-3
输出为:“test 1-2-3”。我检查了jsons是否会在控制台中使用:console.log(vehicle);
显示 - 它有效,它会返回对象数组。
我做错了什么?任何想法如何修复我的代码?
答案 0 :(得分:2)
您有错误:
this.vehicleService.getVehicle().subscribe(vehicle => {
this.vehicle = vehicle;
})
但在您的HTML中,请参考let vechicle of vehicles
你应该添加一个&#34; s&#34;到您的订阅this.vehicle
,如下:
this.vehicleService.getVehicle().subscribe(vehicle => {
this.vehicles = vehicle;
})
编辑:忘了将局部变量vehicle: Vehicle[]
更改为vechicles: Vehicle
,但是你自己想出来了! ;)