1
我的老闆決定將Angular2實施到我們的項目中。我非常喜歡這項技術。我試圖從url中顯示JSON,但結果並不如我預期的那樣。 * ngFor不顯示任何數據。Angular2 - 無法顯示json對象
這是代碼:
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);
- 它工作,它返回對象數組。
我在做什麼錯?任何想法如何解決我的代碼?
嘿,它的工作原理!我將'vehicle:Vehicle []'改爲'vehicles:Vehicle [];'並應用了您的建議。我感到羞愧,我犯了這麼一個小錯誤。謝謝。 – Haseoh
不客氣,有時你只需要新鮮的眼睛! :) – Alex