简体   繁体   中英

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)

您需要在构造函数中注入 http 不要声明为变量类型,

constructor(private http: HttpClient) { }

DEMO

import HttpClientModule

app.module.ts

   imports: [
        HttpClientModule
    ]

workers.component.ts

constructor(private http: HttpClient) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM