Angular 2接口抛出非现有属性的错误

时间:2017-06-01 10:14:38

标签: javascript angularjs

我有一个Angular 2界面 books.ts

export interface Books {
artists: Object;
tracks: Object;
}

这是我的服务文件,我使用http请求 searchService.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Books } from 'app/pages/search-results/books';
import 'rxjs/add/operator/map'

@Injectable()
export class SearchService {

constructor(private _http:Http) { }


 getBook(keyword): Observable<Books[]>{
  return this._http.get('https://api.spotify.com/v1/search?q=' + keyword + '&type=track,artist')
  .map((response: Response) => <Books[]> response.json());
 }
}

这是我使用界面 searchResults.ts

的组件
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SearchService } from 'app/shared/search/search.service';
import { Books } from 'app/pages/search-results/books';


@Component({
 selector: 'app-search-results',
 templateUrl: './search-results.component.html',
 styleUrls: ['./search-results.component.css'],
 providers: [SearchService]
 })
export class SearchResultsComponent implements OnInit {
keyword: any;
sub: any;
books: Books[];
errMessage: string;
arists: Object;

constructor(private _route: ActivatedRoute, private _router: Router,        private _search: SearchService) { }

ngOnInit() {
 this.sub = this._route
  .queryParams
  .subscribe(params => {
    // Defaults to 0 if no query param provided.
    this.keyword = params['keyword'] || 0;
    this.getBooks(this.keyword);
  });

// 
}

getBooks(value) {
this._search.getBook(value)
  .subscribe(
  res => {
    this.books = res;
    console.log(res.artists);
  },
  error => { this.errMessage = <any>error }
  );
 }

}

当我尝试安装 res.artists 时出现错误。该错误表示 Property&#39;艺术家&#39;类型&#39;图书[]&#39; 上不存在。我是Angular 2的新手,并不知道如何解决这个问题。

回复看起来像是

{artists:{limit: 20, item:[]}, tracks:{limit: 20, item:[]}}

3 个答案:

答案 0 :(得分:0)

我不确定,但我认为你试图通过收藏书来获得res.artist。您可以通过for或者res [0] .artist来检查它以获得具体的艺术家。

答案 1 :(得分:0)

SearchService 中的

getBook 函数返回一个Books对象数组(Books []) 所以, SearchResultsComponent 中getBooks函数中的 res 将是一个图书数组。

您可以console.log(res)查看详细信息,如果您想要访问艺术家,请尝试使用res[0].artists如果res不是空数组

答案 2 :(得分:0)

问题是我在响应中获取了Object,并将其分配给导致错误的Array。我只是将两种类型都改为对象,它解决了我的问题。

从此

books: Books[];

到此

books: Books;