ccc

Angular 4: Servicios Get


Vamos a obtener los datos de prueba de:
https://jsonplaceholder.typicode.com/users

En el index.html añadir el CDN de Bootstrap

Creamos nuestra carpeta models (si no existe ya de antes) y dentro de ella:
ng generate class Users
ng generate class Address

models/users.ts:
import { Address } from "./address";
export class Users {
    id: number;
    name: string;
    username: string;
    email: string;
    address: Address;
}

models/address.ts:
export class Address {
    street: string;
    city: string;
}

En app.component.ts:
...
import { Http } from '@angular/http';
...
export class AppComponent {
  title = 'Hola holita';
  Users:Array<Users>;

  constructor(private http: Http) {
    this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(resp => this.Users = resp.json());
  }
}

En app.component.html:
...
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Username</th>
        <th>Email</th>
        <th>Street</th>
        <th>City</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of Users">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.username}}</td>
        <td>{{item.email}}</td>
        <td>{{item.address.street}}</td>
        <td>{{item.address.city}}</td>
      </tr>
     
    </tbody>
  </table>
</div>

En app.module.ts:
...
import { HttpModule } from '@angular/http';
...
imports: [
    BrowserModule,
    HttpModule
  ],

No hay comentarios:

Publicar un comentario