weixin_33694172 2018-08-23 10:26 采纳率: 0%
浏览 20

角度6:http得到回应

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)

  • 写回答

2条回答 默认 最新

  • 衫裤跑路 2018-08-23 10:28
    关注

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

    constructor(private http: HttpClient) { }
    

    DEMO

    评论

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn