Search code examples
ajaxangulartypescripthttpget

Angular 6: http get response


I'm new to Angular. I'm trying to get a simple http get request and get this JSON: https://jsonplaceholder.typicode.com/users , specifically I want to loop the names only.

In the app.module.ts I added the HttpClientModule:

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

In the workers.component.ts, this is what I have:

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

  }

}

The workers.component.html, is very 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>

Currently, I just get the error:

ERROR TypeError: Cannot read property 'get' of undefined at WorkersComponent.push../src/app/workers/workers.component.ts.WorkersComponent.ngOnInit (workers.component.ts:29)


Solution

  • You need to inject http inside the constructor do not declare as a variable type,

    constructor(private http: HttpClient) { }
    

    DEMO