我正在学习Angular并试图进行API调用,但为什么我得到这个错误:
error TS2339: Property 'name' does not exist on type 'never'.
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
li: any;
lis = [];
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http
.get('http://www.mocky.io/v2/5ea172973100002d001eeada')
.subscribe((Response) => {
console.log(Response);
this.li = Response;
this.lis = this.li.list;
});
}
}
<h1>Title</h1>
<div *ngFor="let e of lis">
<p>{{ e.name }}</p>
</div>
<router-outlet></router-outlet>
您需要指定http响应的类型:
type Person = { name: string };
type Response = { list: Person[] };
this.http.get<Response>('http://www.mocky.io/v2/5ea172973100002d001eeada')
.subscribe((response) => {
console.log(response);
this.lis = response.list;
});
你应该试试这个:
<p>{{ e?.name }}</p>
我认为你尝试渲染属性之前,它收到。