B
B
beta-it2017-03-22 14:17:52
Angular
beta-it, 2017-03-22 14:17:52

How to cache API requests in Angular 2?

There is an Angular 2 application that makes a fairly large number of requests to the server when navigating through the components, does anyone know how this can be avoided?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
ozknemoy, 2017-03-22
@beta-it

here is the method from the service. key for each url. there is another way as in the angular-universal repo. it's smarter there, but you don't have to repeat the requests that the server made node
getUsersActivity(forceRefresh?:boolean) {
return this.getWithCache (
'user-activity',
'usersActivity$', forceRefresh)
};

getWithCache(url, key, forceRefresh?:boolean):any {
     
       if (!this[key]) {
            this[key] = new ReplaySubject(1)
        }

        // If the Subject was NOT subscribed before OR if forceRefresh is requested
        if (!this[key].observers.length || forceRefresh) {
            this.get(url).subscribe(
                (data) => this[key].next(data),
                (error) => {
                    this[key].error(error);
                    // Recreate the Observable as after Error we cannot emit data anymore
                    this[key] = new ReplaySubject(1);
                }
            );
        }

        return this[key];
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question