简体   繁体   English

“从不”类型上不存在属性“名称”

[英]Property 'name' does not exist on type 'never'

I am learning Angular and trying to make an API call but why do I get this error:我正在学习 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>

You need to specify the type of the http response:您需要指定 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;
      });

You sould try this:你应该试试这个:

  <p>{{ e?.name }}</p>

I think you try render the property before it received.我认为您尝试在收到该属性之前对其进行渲染。

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

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