我收到错误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]
);
}
}
My Plunker但是在“英雄之旅”中它运作良好
答案 0 :(得分:5)
问题很简单。它不适合您,因为您的服务使用字符串解析而不是数组:
getArticle(id: number) {
return Promise.resolve('./articles.json').then(
articles => articles.filter(article => article.id === id)[0]
);
}
注意,Promise.resolve('./articles.json')
(documentation)以字符串解析。
正确的代码是这样的:
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]);
}
}
答案 1 :(得分:1)
我想这是因为在某些情况下,你获得的内容不是数组而是对象。因此,您无法使用filter
方法,因为它是Array
的方法。
但我同意埃里克的意见,一个重复你错误的傻瓜会很棒!