【问题标题】:Unable to loop array of objects in angular6无法在angular6中循环对象数组
【发布时间】:2019-02-22 00:30:00
【问题描述】:

我正在尝试从 omdbapi 获取电影数据,但我无法在 html 中打印此值

.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)
      })
  }
}

控制台价值

【问题讨论】:

    标签: arrays angular typescript observable angular6


    【解决方案1】:

    您可能在results 的模板中使用*ngFor。但是由于您将data 分配给results 并且data 是一个对象,所以它会给出错误,因为*ngFor 假定了一个迭代数据结构。

    从您的屏幕截图中可以看出,您的data 上有一个Search 数组。

    this.results = data; 更改为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');
      }
    
    }
    

    这里有一个Sample StackBlitz 供您参考。

    【讨论】:

    • 得到错误属性搜索不存在类型对象错误
    • 奇怪。您正在控制台上打印数据,它在控制台上给出Search,这是一个数组
    • 这是html
      • {{result.Title }}
    • subscribe 内将data 更改为(data: any)。我已经更新了答案
    【解决方案2】:

    您可以使用keyvalue 管道实现此目的,如下所示:

    <div *ngFor="let item of results | keyvalue">
       <b>{{item.key}}</b> : <b>{{item.value}}</b>
    </div>
    

    【讨论】:

      【解决方案3】:

      您在响应中得到了一个对象。您需要像这样在 *ngFor 循环中使用 ? 运算符来获取异步 http 服务的数组。

      <ul>
         <li *ngFor="let result of results?.Search">{{result.Title }}</li>
      </ul>
      

      你可以像这样显示totalResults

      <span>Total: {{results?.totalResults}}</span>
      

      【讨论】:

        猜你喜欢
        • 2019-03-21
        • 2019-02-12
        • 1970-01-01
        • 1970-01-01
        • 2016-11-02
        • 2021-11-29
        • 2019-09-18
        • 2014-08-11
        • 2012-06-09
        相关资源
        最近更新 更多