.filter不是一个函数Angular2 [英] .filter is not a function Angular2

查看:61
本文介绍了.filter不是一个函数Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到错误EXCEPTION: TypeError: articles.filter is not a function 在我的服务

i getting an error EXCEPTION: TypeError: articles.filter is not a function in my service

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 but in "Tour of Heroes" it works fine

推荐答案

问题很简单.它对您不起作用,因为您的服务使用 string 而不是数组来解析:

The problem is quite simple. It doesn't work for you because your service resolves with a string not an array:

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

注意,Promise.resolve('./articles.json')(文档)以字符串解析.

Note, Promise.resolve('./articles.json') (documentation) which resolves with string.

正确的代码如下:

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不是一个函数Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆