【问题标题】:Angular 4 Displaying Data From Rest APIAngular 4 显示来自 Rest API 的数据
【发布时间】:2018-02-08 17:13:29
【问题描述】:

我在显示来自本地 express.js REST API 的数据时遇到问题,其结构如下:

 people: [{ surname: 'testsurname', name: 'testname', email: 
 'testmail@gmail.com', status: 1, activity: 'Office' }

我有一个获取数据的人员服务,它看起来像这样:

export interface People {
  surname: String;
  name: String;
  email: String;
  status: Boolean;
  activity: String;
}

@Injectable()
export class PeopleService {

private _peopleURL = "http://localhost:8080/api/people";

constructor(private http: HttpClient) {
console.log('init PS')
}

getPeople(): Observable<People[]> {
return this.http
    .get(this._peopleURL)
    .map((response: Response) => {
        return <People[]>response.json();
    })
  }


}

这是我的 PeopleComponent.ts 代码

export class PeopleComponent implements OnInit {
  _peopleArray: People[];

  constructor(private ps: PeopleService)
   { }

   getPeople(): void {
    this.ps.getPeople()
        .subscribe(
            resultArray => this._peopleArray = resultArray,
            error => console.log("Error :: " + error)
        )
}


  ngOnInit(): void {
    this.getPeople();
  }

现在我正在尝试在我的“人物”component.html 中显示数据(即名称),如下所示:

<div> {{people.name}} </div>

当我启动我的应用程序时,我收到一条错误消息

'TypeError: Cannot read property 'name' of undefined at Object.eval [as updateRenderer] 

谁能向我解释我错过了什么以及我需要做什么才能显示数据?

【问题讨论】:

  • 你试过打印 people[0].name 吗?因为它是一个数组
  • @HrishikeshKale 是的,但后来我收到“无法读取未定义的属性 '0'”
  • 如果使用 HttpClient 我建议:返回 this.http.get(this._peopleURL , { observe: 'body', responseType: 'json'});这样你就不需要 .map()
  • _peopleArray.name 将起作用
  • @HrishikeshKale 不幸的是,没有,仍然未定义

标签: angular rest typescript express


【解决方案1】:

您的响应是 json array 。请尝试以下代码 sn-p。

<div *ngFor ="let p of people">
      <div> {{p.name}} </div>
   </div>

更新

如下所示更改您的服务方法。返回新 HttpClient 的默认值是 Object。它会在内部自动调用response.json()

getPeople(): Observable<People[]> {
    return this.http
      .get<People[]>(this._peopleURL);

  }

查看以下工作演示

WORKING DEMO

【讨论】:

  • 谢谢!现在我收到一条错误消息,说“Error :: TypeError: response.json is not a function”......我做错了什么的任何标题?
  • 尝试导入'rxjs/add/operator/map' 应该可以解决问题。
  • 谢谢你,这对我很有帮助!
【解决方案2】:

您的组件中甚至没有“people”字段,而是将其设置为“_peopleArray”。

但即使你把它改成

<div> {{_peopleArray.name}} </div>

它仍然不起作用,因为 _peopleArray 是一个数组。

您可以使用 *ngFor 遍历数组对象,或者像这样只访问数组的第一个或第 n 个元素

<div> {{_peopleArray[0].name}} </div>

【讨论】:

  • 谢谢!现在我收到一条错误消息,说“Error :: TypeError: response.json is not a function”......我做错了什么的任何标题?
  • 在尝试使用 .json() 访问数据之前,您可以 console.log 记录您的响应吗?
  • 你不应该从你的 Observable 中“返回”任何东西。将您的服务方法更改为:" return this.http .get(this._peopleURL) .map((response: Response) => { response.json(); }) } "
【解决方案3】:

您应该这样做以打印您的 JSON 结构“对象数组

   <div *ngFor ="let person of _peopleArray">
      <div> {{person.name}} </div>
   </div>

【讨论】:

  • 这里不需要安全导航操作员 :)
猜你喜欢
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多