jx1986
jx1986

Reputation: 53

how to filter json correctly with HttpClient angular 4

i am having problem migrating from Http to HttpClient, this is the code that i use

constructor(public navCtrl: NavController, public http: HttpClient, private alertCtrl: AlertController) {

 this.http.get('http://example.com/date.php')
.subscribe(data => {
  this.posts = data;
  this.postsfilter = data.filter(item => item.date == todayDate);

 });

 }

i have included import 'rxjs/add/operator/filter'; but still getting error : Property 'filter' does not exist on type 'Object'. how to filter the return json file correctly?

Upvotes: 2

Views: 3659

Answers (2)

Eliseo
Eliseo

Reputation: 57971

"i have included import 'rxjs/add/operator/filter'; but still getting error : Property 'filter' does not exist on type 'Object'. how to filter the return json file correctly?" Because you don't say that data is an array

 this.http.get('http://example.com/date.php')
      .subscribe((data:any[]) => { //<--say that you received an array
         this.posts = data;
         //Here filter is filter of an ARRAY, not Rxjs
         this.postsfilter = data.filter(item => item.date == todayDate);
      });

Upvotes: 0

Orlandster
Orlandster

Reputation: 4858

By calling data.filter() you will access the Array.prototype.filter() method and not the RxJS's filter method. In your case, data contains an object which does not have a method filter. That's causing the error.

To use RxJS's filter you need to chain it to your Observable with the . notation.

That's how it looks like:

 this.http.get('http://example.com/date.php')
  .map(item => this.postsfilter = item)
  .filter(item => item.date === todayDate) // probably you would also want to go for strict equality
  .subscribe(data => {
    this.posts = data;
  });

Notice: Since RxJS 5.5 you are able to use the pipe method. THis basically changes the way you chain RxJS operators. Learn more about it here: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44

Upvotes: 2

Related Questions