.filter不是Angular2的函数

Sli*_*lip 2 angular

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]
     );
  }
 }
Run Code Online (Sandbox Code Playgroud)

我的Plunker但在"英雄之旅"中它运作良好

dfs*_*fsq 5

问题很简单.它不适合您,因为您的服务使用字符串而非数组解析:

getArticle(id: number) {
  return Promise.resolve('./articles.json').then(
    articles => articles.filter(article => article.id === id)[0]
  );
}
Run Code Online (Sandbox Code Playgroud)

注意,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]);
  }
}
Run Code Online (Sandbox Code Playgroud)