Search code examples
angulartypescriptfirebase-realtime-databaseobservableangularfire

Firebase Observable scan() and return if meets condition


In Firebase I have articles objects, like:

articles
 UNIQUE_KEY
  title: 'Some title'
  validUntil: '2017-09-29T21:00:00.000Z'
 UNIQUE_KEY
  title: 'Other title'
  validUntil: '2017-10-29T21:00:00.000Z'

Now I want to take those whose validUntil (date) is still upcoming, so in service I do:

  getValidArticles(): Observable<Article[]> {
    return this.afDb.list('articles').do(console.log)
      .scan((article) => { 
        if (new Date(article.validUntil).getTime() >= new Date().getTime()) {
          return article;
        }
      })
  } 

And looks like it works well, but as you see I .do(console.log) in that function and what's strange is that I get two outputs in console - two identical objects. Am I doing it wrong?


Solution

  • I'm not sure why your code isn't working. But even if it would work, it is going to be less than ideal: you're downloading all data and then remove the outdated data on the client. This means that you're downloading data that your users won't see, which is wasteful.

    I'd recommend to instead filter the data on the server, as shown in the AngularFire2 documentation:

    return this.afDb.list('articles', {
      query: {
        orderByChild: 'validUntil',
        startAt: '2017-09-29T21:00:00.000Z' 
      }
    });