[英]Unable to loop array of objects in angular6
I'm trying to fetch movie data from omdbapi but i'm not getting able to print this value in html 我正在尝试从omdbapi获取电影数据,但无法在html中打印此值
.ts .TS
import { Component, } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _httpClient: HttpClient) {}
results: any = [];
getMovies(title) {
`enter code here`
this._httpClient.get("http://www.omdbapi.com/?apikey=d5dc2a5a&s=" + title)
.subscribe((data) => {
this.results = data;
//this.results.Search;
console.log(this.results)
})
}
}
Console value 控制台值
You're probably using *ngFor
in your template on results
. 您可能在
results
的模板中使用*ngFor
。 But since you're assigning data
to results
and data
is an Object, it's giving an error as *ngFor
assumes an iterative Data Structure. 但是由于将
data
分配给results
并且data
是对象,因此*ngFor
假定迭代数据结构会产生错误。
As can be seen from your Screenshot, there's a Search
array on your data
. 从屏幕截图可以看出,
data
上有一个Search
数组。
Change this.results = data;
更改
this.results = data;
to this.results = data.Search;
到
this.results = data.Search;
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _httpClient: HttpClient) {}
results: any = [];
getMovies(title) {
this._httpClient.get("https://www.omdbapi.com/?apikey=157f9eb7&s=" + title)
.subscribe((data: any) => {
this.results = data.Search;
console.log(this.results);
})
}
ngOnInit() {
this.getMovies('The Dark Knight');
}
}
Here's a Sample StackBlitz for your ref. 这是供您参考的示例StackBlitz 。
You can achieve this using keyvalue
pipe as below: 您可以使用
keyvalue
管道实现此目标,如下所示:
<div *ngFor="let item of results | keyvalue">
<b>{{item.key}}</b> : <b>{{item.value}}</b>
</div>
You are getting an object in your response. 您在响应中得到一个对象。 You need use ?
您需要使用吗? operator in *ngFor loop like this to get array for asynchronous http service.
像这样在* ngFor循环中的运算符可获取用于异步http服务的数组。
<ul>
<li *ngFor="let result of results?.Search">{{result.Title }}</li>
</ul>
and you can display totalResults
like this : 并且您可以显示
totalResults
像这样:
<span>Total: {{results?.totalResults}}</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.