繁体   English   中英

Angular 6:http 获取响应

[英]Angular 6: http get response

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

  }

}

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

目前,我只是收到错误:

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

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

constructor(private http: HttpClient) { }

DEMO

导入HttpClientModule

app.module.ts

   imports: [
        HttpClientModule
    ]

worker.component.ts

constructor(private http: HttpClient) { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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