我是新来的角度。我试图得到一个简单的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>
目前,我只得到一个错误:
错误类型错误:无法读取未定义的属性“get”
在workers component.push../src/app/workers/workers.component.ts.workerscomponent.ngonit(workers.component.ts:29)
最佳答案
您需要在构造函数中注入HTTP,不要声明为变量类型,
constructor(private http: HttpClient) { }
DEMO