Angular 7:"对象 "类型上不存在属性 "data"。

问题描述 投票:0回答:1

我使用的是Angular7,并按照这里的步骤进行操作。https:/coursetro.compostscode171Angular-7-Tutorial--Learn-Angular-7-by-Example。

但是得到的错误数据却没有。这是下面的错误。

src/app/home/home.component.html:18:29 - error TS2339: Property 'data' does not exist on type 'Object'.

18     <li *ngFor="let user of users.data">
                               ~~~~~~~~~~

  src/app/home/home.component.ts:6:16
    6   templateUrl: './home.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component HomeComponent.

我试图测试代码并生成服务,但我一直在home.component.htmlhome.component.ts中得到错误信息。

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  users: Object;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getUsers().subscribe(data => {
      this.users = data
      console.log(this.users)
    })
  }

}

home.component.html

<ul *ngIf="users">
    <li *ngFor="let user of users.data"> 
      <!-- <img [src]="user.avatar">
      <p>{{ user.first_name }} {{ user.last_name }}</p> -->
      <p> {{user}}</p>
    </li>
  </ul>

data.service.ts

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

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

  constructor(private http:HttpClient) { }
  getUsers() {
    return this.http.get('https://reqres.in/api/users');
  }

}

这和例子中的代码一模一样,怎么解决?

angularjs angular angular7
1个回答
0
投票

试试这个

users: any;

或确保用户、数据对象

export class User {
 bla : string,
 data : Array<Data>
}

export class Data{
 blabla : string,
 blablabla : number
}

这样

然后

users : User = new User()

我希望它帮助


0
投票

这是一个编译问题,不是运行时问题。这意味着你的Typescript强制执行的类型安全可能存在问题。

我们可以看到,你已经将类型安全化了 users 作为 Object. 然而, data 不存在于通用类上 Object. 你可以做的是只投 users 不同。

users: {
  data: {
    first_name: string;
    last_name: string;
  }[];
}

所以正如你所看到的,我们正在描述一个叫做 users 带着财产 data. data 是一个对象数组({}[]),其中包含一个 first_namelast_name 属性。


0
投票

为用户对象定义类型,如下图所示。

user: {
   data: any;
}

然后在HomeComponent中用空数组初始化用户对象。

© www.soinside.com 2019 - 2024. All rights reserved.