1

my boss decided to implement Angular2 into our project. I'm preety new to this technology. I'm trying to display JSON from url, but the result is not as I expected. *ngFor doesn't display any data.

This is the code:

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

The output is: "test 1-2-3". I checked if the jsons will be displayed inside the console using: console.log(vehicle); - it worked, it returns Array of Objects.

What am I doing wrong? Any ideas how to fix my code?

1 Answer 1

2

You have an error:

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

but in your html you refer to let vechicle of vehicles

You should add an "s" to your this.vehicle to your subscription like so:

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! ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Hey, it works! I changed vehicle: Vehicle[] to vehicles: Vehicle[]; and applied your suggestion. I feel ashamed I made such a small mistake. Thank you.
You are welcome, sometimes you just need fresh eyes! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.