Búsqueda de sitios web

ajax - Angular 6: respuesta http get


Soy nuevo en Angular. Estoy intentando hacer una simple solicitud http get y obtener este JSON: https://jsonplaceholder.typicode.com/users, específicamente quiero recorrer solo los nombres.

En el app.module.ts añadí el HttpClientModule:

import { HttpClientModule } from '@angular/common/http';

En el workers.component.ts, esto es lo que tengo:

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-workers',
  templateUrl: './workers.component.html',
  styleUrls: ['./workers.component.css']
})
export class WorkersComponent implements OnInit {
  showList = [];
  http: HttpClient;

  constructor() { }

  ngOnInit() {
    //THIS IS WHAT I TRIED
    let obs = this.http.get('https://jsonplaceholder.typicode.com/users');
    obs.subscribe(() => console.log('Got the response, yay.'));

    //Later I would try to get the name with response[0].name

  }

}

El workers.component.html es muy simple:

          <table class="table">
          <thead>
              <tr>
                <th scope="col">Name</th>
              </tr>
            </thead>
            <tbody>
              <tr> 
                <td *nfFor="let name of names">{{name}}</td>    
              </tr>
            </tbody>         
      </table>

Actualmente, sólo recibo el error:

ERROR TypeError: No se puede leer la propiedad 'get' de undefined en WorkersComponent.push../src/app/workers/workers.component.ts.WorkersComponent.ngOnInit (workers.component.ts:29)

Respuesta #1

Necesitas inyectar http dentro del constructor, no declararlo como un tipo de variable.

constructor(private http: HttpClient) { }

DEMO

Respuesta #2

importar HttpClientModule

app.module.ts

   imports: [
        HttpClientModule
    ]

trabajadores.componente.ts

constructor(private http: HttpClient) { }