1

I'm getting an observable list of objects from firebase, then subscribe to it (via async pipe) in my component. For now everything works perfect. List is only reloaded when something changes.

//getting observable list from firebase
//ArticlesService
    public getAllArticles(limit:number = 100):Observable<Article[]>
     {
        return this.af.database.list("/articles/", {
          query: {
            limitToFirst: limit
          }
        }).map( (arts) => {
          return arts.map(art => {
            return Article.unpack(art); //creating an Article object
          })
        })
     }
//ArticlesComponent
ngOnInit() {
    this.articles$ = this.artService.getAllArticles();
 }
<app-articles-list [articles]="articles$ | async"></app-articles-list>

However, when I use Angular2 router and navigate out from the route and then back - seems like all the same data is loaded once again from the firebase which creates a rendering delay and traffic overhead.

I guess it happens because when I navigate out and then back, subscription is recreated and data is asked like if it wasn't already loaded.

So, I was thinking what would be the way to avoid such behaviour? Could be caching, could be something else. Not really sure at the moment.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

3

Solved it! This article helped a lot: http://www.syntaxsuccess.com/viewarticle/caching-with-rxjs-observables-in-angular-2.0

//ArticleService
private allArticles$:Observable<Article[]>; 

public getAllArticles(limit:number = 100):Observable<Article[]>
  {
    if(!this.allArticles$)
    {
      this.allArticles$ = this.af.database.list("/articles/", {
        query: {
          limitToFirst: limit
        }
      }).map( (arts) => {


        return arts.map(art => {
          let unpacked = Article.unpack(art);
          return unpacked;
        })
      }).publishReplay(1).refCount();
    //for all new subscriptions replay emitted values
    }
    return this.allArticles$;
  }