角度:错误-TS2339:类型“ {}”上不存在属性“名称”

时间:2020-09-08 19:17:50

标签: angular typescript

我知道你们中很多人会说这是一个重复的问题,但是我的担心有所不同。我想在网页上显示从jsonplaceholder.com获得的虚假API的数据。我已经在使用该API的地方创建了服务,以下是我的文件和错误。

error- TS2339: Property 'name' does not exist on type '{}'.

api.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private _http:HttpClient) { }
  names(): Observable<any>{
    return this._http.get('https://jsonplaceholder.typicode.com/users');
  }
}

component.ts:

import { Component, OnInit,Input } from '@angular/core';
import { MessageserviceService } from '../services/messageservice.service';
import { ApiService } from '../api.service';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
  childdata;
  itemname;
  price:boolean=false;
  list={};
  constructor(private http:ApiService) { }

  ngOnInit():any {
    this.http.names().subscribe(data=> this.list=data)
  }
}

component.html:

<ul>
    <li>{{list.name}}</li>
</ul>

2 个答案:

答案 0 :(得分:2)

您在响应中得到的是一个数组而不是一个对象,为了显示这些详细信息,您需要使用ngFor

<ul>
    <li *ngFor="let listObj of list">
      {{ listObj?.name}}
    </li>
 </ul>

答案 1 :(得分:0)

这是因为list是一个数组。从jsonplaceholder返回的数据经过Angular HttpClient解析后,将转换为需要手动遍历的javascript数组。

您可以通过更改app.component.html中的代码以遍历数组来实现:

<ul *ngFor="let itm of list">
    <li>{{itm.name ? itm.name : ''}}</li>
</ul>

如果您不想使用三元运算符,则可以始终使用pipe

相关问题