访问从OMDBAPI返回的JSON对象的属性

时间:2019-08-13 12:00:04

标签: javascript json angular typescript angular7

我想正确显示以下显示的搜索结果

  1. 访问“响应”变量以检查是否发生任何错误
  2. 访问对象数组并将其分配/转换为searchItems数组

但是我不确定如何正确地从返回的JSON对象中读取这些值,仅分配数据[i]显然是行不通的。任何帮助或其他想法非常感谢。 我省略了类声明和导入,以便于阅读。

//The API response



{…}
​
Response: "True"
​
Search: (10) […]
​​
0: Object { Title: "Batman Begins", Year: "2005", imdbID: "tt0372784", … }
​​
1: Object { Title: "Batman v Superman: Dawn of Justice", Year: "2016", imdbID: "tt2975590", … }
​​
2: Object { Title: "Batman", Year: "1989", imdbID: "tt0096895", … }
​​
3: Object { Title: "Batman Returns", Year: "1992", imdbID: "tt0103776", … }
​​
4: Object { Title: "Batman Forever", Year: "1995", imdbID: "tt0112462", … }
​​
5: Object { Title: "Batman & Robin", Year: "1997", imdbID: "tt0118688", … }
​​
6: Object { Title: "The Lego Batman Movie", Year: "2017", imdbID: "tt4116284", … }
​​
7: Object { Title: "Batman: Under the Red Hood", Year: "2010", imdbID: "tt1569923", … }
​​
8: Object { Title: "Batman: The Dark Knight Returns, Part 1", Year: "2012", imdbID: "tt2313197", … }
​​
9: Object { Title: "Batman: The Killing Joke", Year: "2016", imdbID: "tt4853102", … }
​​
length: 10
​​
<prototype>: Array []
​
totalResults: "303"

//searchItem.ts, used to display the needed object properties as returned from the api

export interface SearchItem {
    title: string;
    year: string;
}


//add.service.ts extract

fetchMovies(searchTitle: String) {

    var searchUrl: string = //insert working url here
    console.log(searchUrl);
    return this.httpCli.get(searchUrl);
  }


//add.component.ts extract

results: SearchItem[];

  showItems() {
    this.addService.fetchMovies('batman').subscribe(data =>{
      console.log(data);
      if(data[0] === "True"){ //intercept if error = true
        alert("error");
      }
      this.results = data[1]; //assign the results to the SearchItem-Array
    });
  } 

//add.component.html extract

<div *ngFor="let result of results">
  <p>{{ result.Title }}  {{ result.Year}}</p>
</div>

0 个答案:

没有答案
相关问题