0

Im workiing with Angular 8, Ionic 4 and trying to reduce server calls by caching

I have a search service that returns an Observable.

I want to know if I can use the router to access functions in that service.

For example: in routes something like {path: 'api/:func/:term', component: ApiComponent }

then in a page I would make a request to hit the api route like: http.get('/api/search-cars/corvette') would route to a searchCars(term:string) function and take corvette as the argument. This is a filter function, returning a portion of the array that is in the RXJS store.

The purpose of this would be to be able to cache that request url so the server isn't hit everytime data is sorted.

When I try to hook something up I get a 404 error. Is there a way to create an internal API?

1
  • Show us what you've tried. Commented Feb 22, 2020 at 2:26

2 Answers 2

1

I think you don't need fake http requests do to that. As you said you have a service layer, so you may storage the sever result at moment you made the first request to the endpoint. Some ideas here:

1 - ShareReplay: where you keep the request for the subscribers doc

2 - Storage: Save the request data at client storage (like localstorage or something else)

  listUsers(): Observable<User[]>{

    const storageUsers = localStorage.getItem('users');

    return storageUsers 
    ? of<User[]>(storageUsers) 
    : this.http.get<User[]>(`some-end-point/users`)
       .pipe(
         tap(users => localStorage.setItem('users', users))
       );      
  }

3- Redux Doc

Sign up to request clarification or add additional context in comments.

Comments

1

The router is used for displaying components given the location in the browser address bar. There are a few ways you can store past requests, but a service could be sufficient for your use case.

Given the information you shared, I've made some assumptions about your API usage and the StackBlitz I'm sharing would need more work to be a complete solution, but you can have a look at a dynamic "caching" service here: https://stackblitz.com/edit/angular-vhijkx

I've used a map to store responses for past requests, but you can use individual variables as well, given the use case. To persist the "cache" past a page load, it can be stringified and placed in localStorage or sessionStorage as well.

private cache: Map<string,any[]> = new Map();

getRequest(endpoint: string, termQuery: string): Observable<any> {
  const url = `${this.apiBase}/${endpoint}`,
    params = new HttpParams().set(this.term, termQuery),
    storeId = `${endpoint}:${termQuery}`,
    cache = this.cache.get(storeId);

  if (cache) {
    console.log('fetched from cache');
    return of(cache);
  } else {
    console.log('fetched from API');
    return this.http.get(url, {params}).pipe(
      tap(response => {
        this.cache.set(storeId,response);
      })
    );
  }
}

This method first checks if a cached entry already exist. If so, it returns an Observable thereof instantly, otherwise it does the API request and when the response is received, the cache is set and the Observable returned.

3 Comments

Thanks so much for your reply. I see that I failed to be clear though. I am not concerned about how to cache the request. What I am failing to be able to so is set up a route that goes to a component for the sole purpose of retrieving data. This component will not be displayed but only return data. I don't know how to make that happen. The reason I use a component is because as far as I can tell, the router requires a component. So I want to use http.get to hit a route in the app and return data. I think I have to use a component which will in turn call a service. Sorry for the confusion.
It doesn't sound like there isn't any reason to try and achieve this pseudo-router request though? Why not just access the functions in your service that return observables directly?
mainly because Ionic configuration makes it really easy to cache data from a web request. If I can do http.get and return the data Ionic takes care of the rest. In that scenario I don't have nearly as much work to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.