角度6:http得到回应

时间:2018-08-23 10:26:17

标签: ajax angular typescript http get

我是Angular的新手。我试图获取一个简单的http get请求并获取此JSON:https://jsonplaceholder.typicode.com/users,特别是我只想循环命名。

app.module.ts 中,我添加了HttpClientModule:

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

workers.component.ts 中,这就是我所拥有的:

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

  }

}

workers.component.html 非常简单:

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

当前,我刚得到错误:

错误TypeError:无法读取未定义的属性“ get”     在WorkersComponent.push ../ src / app / workers / workers.component.ts.WorkersComponent.ngOnInit(workers.component.ts:29)

2 个答案:

答案 0 :(得分:1)

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

constructor(private http: HttpClient) { }

DEMO

答案 1 :(得分:0)

导入HttpClientModule

  

app.module.ts

   imports: [
        HttpClientModule
    ]
  

workers.component.ts

constructor(private http: HttpClient) { }