Slip
Slip

Reputation: 949

.filter is not a function Angular2

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

Upvotes: 2

Views: 16790

Answers (2)

dfsq
dfsq

Reputation: 193301

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]
  );
}

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

Correct code would be something like this:

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]);
  }
}

Upvotes: 5

Thierry Templier
Thierry Templier

Reputation: 202346

I guess that it's because in some cases, the content you get isn't an array but an object. So you can't use the filter method since it's a method of Array.

But I agree with Eric, a plunkr reproducing your error would be great!

Upvotes: 2

Related Questions