List data from Json with Angular 2

1

Considering that I have a Json coming from a Url (' link '). I created a service to get this object:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';

    @Injectable()
    export class PlanosService {
      //get Json Servicos
        planos: Object[] = [];
        constructor(http: Http) {
          http
          .get('https://api.carguruclub.com/v1/servicos')
          .map(res => res.json())
          .subscribe(planos => {
            this.planos = planos;
            console.log(this.planos);
          }, erro => console.log(erro));
        }
    }

So far so good. However, my question is on how to list the elements of this object .. For example, I wanted to get {{products.name}} and display that json snippet and in my component. I do not understand very well the paths that I must follow, since I am a beginner. Thank you in advance.

    
asked by anonymous 17.07.2017 / 21:54

1 answer

1

Here's a plunker I created as an example: link

You need in the component to insert the service created as a provider

import {PlanosService} from 'src/planos.service'

@Component({
  selector: 'my-app',
  templateUrl: 'src/main.html',
  providers: [PlanosService]
})

After doing this, in the constructor you reference the service.

  constructor(public prdService: PlanosService) {

  }

As you are already putting the variable inside the html service you use the reference created in the above constructor as a * ngFor to loop

<table class="table table-bordered table-striped">
  <thead>
    <tr>
      <th>Name</th>
      <th>Descrição</th>
      <th>Preço</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let plano of prdService.planos.products">
      <td>{{plano.name}}</td>
      <td>{{plano.desc}}</td>
      <td>{{plano.price}}</td>
    </tr>
  </tbody>
</table>

Remembering that to use the map it is necessary to import the rxjs map operator

import 'rxjs/add/operator/map'
    
28.07.2017 / 16:33