List Json Data with Angular 2

Asked

Viewed 1,602 times

1

whereas I have a Json coming from a Url ('https://api.site.com.br/v1/servicos'). I created a service to pick up 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 how to list the elements of this object.. For example, I wanted to take {{products.name}} and display that chunk of json and in my Component. I do not understand very well the paths I must follow, because I am a beginner. Thank you in advance.

1 answer

1

Follows a plunker I created as an example: https://plnkr.co/edit/uXAKd17lCOdxBzRG6CVs?p=preview

You need in the component to enter the service created as a previous

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) {

  }

Since you are already placing the variable inside the service in html 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 you need to import the rxjs Operator map

import 'rxjs/add/operator/map'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.