[英].filter is not a function Angular2
我收到錯誤EXCEPTION: TypeError: articles.filter is not a function
我的服務中EXCEPTION: TypeError: articles.filter is not a function
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import 'rxjs/Rx';
@Injectable()
export class ArticlesService {
http:Http;
constructor(http:Http) {
this.http = http;
}
getArticle(id: number) {
return Promise.resolve('./articles.json').then(
articles => articles.filter(article => article.id === id)[0]
);
}
}
我的傻瓜,但在“英雄之旅”中效果很好
問題很簡單。 它對您不起作用,因為您的服務使用字符串而不是數組解析:
getArticle(id: number) {
return Promise.resolve('./articles.json').then(
articles => articles.filter(article => article.id === id)[0]
);
}
請注意, Promise.resolve('./articles.json')
( 文檔 )使用字符串解析。
正確的代碼如下所示:
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import 'rxjs/Rx';
@Injectable()
export class ArticlesService {
http: Http;
constructor(http: Http) {
this.http = http;
}
getArticle(id: number) {
return this.http.get('./articles.json')
.map(res => res.json())
.toPromise()
.then(articles => articles.filter(article => article.id === id)[0]);
}
}
我猜這是因為在某些情況下,您獲得的內容不是數組而是對象。 所以您不能使用filter
方法,因為它是Array
的方法。
但是我同意埃里克(Eric)的觀點,重演您的錯誤會很棒!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.