-1

I am learning Angular and trying to make an API call but why do I get this error:

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>
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Kikoanno
  • 91
  • 2
  • 10
  • 4
    `lis = []` has an inferred type of `never[]`, i.e. an array that's _always_ empty. You're using TypeScript, so _use TypeScript_ - specify the properties' types and the expected response payload type, so the compiler can actually help you. – jonrsharpe Jul 07 '22 at 08:44
  • You can reference the name in the template as `e["name"]` without any errors. –  Jul 25 '23 at 05:06

2 Answers2

1

You need to specify the type of the http response:

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;
      });
wlf
  • 3,086
  • 1
  • 19
  • 29
0

You sould try this:

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

I think you try render the property before it received.

mullern
  • 58
  • 4
  • Still not working with ? . – Najam Us Saqib Jan 10 '23 at 09:16
  • 1
    Not downvoting the answer because it can be helpful to someone else: the use of the '?' operator above is used when you know what kind of object you are expecting, but you are not 100% sure that the object itself will arrive. In the case above, placing the '?' after 'e' will make it so that if the object is undefined, the runtime won't crash or show errors of the type 'Cannot read property 'name' of undefined'. This operator, however, doesn't fit the case provided by the poster of the question, which is about variable typings. – JurgenBlitz Feb 02 '23 at 10:53