简体   繁体   English

Angular2-无法显示json对象

[英]Angular2 - cannot display json objects

my boss decided to implement Angular2 into our project. 我的老板决定在我们的项目中实现Angular2。 I'm preety new to this technology. 我不熟悉这项技术。 I'm trying to display JSON from url, but the result is not as I expected. 我正在尝试从url显示JSON,但结果与我预期的不一样。 *ngFor doesn't display any data. * ngFor不显示任何数据。

This is the code: 这是代码:

vehicle.service.ts 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 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 vehicle.html

<div *ngFor="let vehicle of vehicles">
    <h3>{{vehicle.title}}</h3>
    <p>{{vehicle.body}}</p>
</div>
test 1-2-3

The output is: "test 1-2-3". 输出为:“测试1-2-3”。 I checked if the jsons will be displayed inside the console using: console.log(vehicle); 我使用以下命令检查json是否将在控制台内显示: console.log(vehicle); - it worked, it returns Array of Objects. -工作正常,它返回对象数组。

What am I doing wrong? 我究竟做错了什么? Any ideas how to fix my code? 任何想法如何解决我的代码?

You have an error: 您有一个错误:

this.vehicleService.getVehicle().subscribe(vehicle => {
        this.vehicle = vehicle;
})

but in your html you refer to let vechicle of vehicles 但在您的html中,您指的let vechicle of vehicles

You should add an "s" to your this.vehicle to your subscription like so: 您应在this.vehicle的订阅中添加“ s”,如下所示:

this.vehicleService.getVehicle().subscribe(vehicle => {
        this.vehicles = vehicle;
})

Edit: Just forgot to meantion to change the local variable vehicle: Vehicle[] to vechicles: Vehicle , but that you figured out that yourself! 编辑:刚才忘了meantion改变局部变量的vehicle: Vehicle[]vechicles: Vehicle ,但你想通了,你自己! ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM