0

Here is my resolver

@Injectable()
export class FieldsResolver implements Resolve<string[]> {
    private result:Array<string> | null = null;

    constructor(private httpClient:HttpClient) {}

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
        return this.result || this.httpClient.get<Array<string>>('<api_route>')
            .pipe(
                tap(fields => {
                    this.result= fields;
                })
            );
    }
}

As you can see, the data returned by the resolver does not depend on my route. Thus, I don't need to actually do the request to my API every times the route change.

My code above works : it does the request only the first time. And for the next few times it will return the cached result.

I was just wondering if there was a more rxjx way to do that.

dc-p8
  • 784
  • 1
  • 6
  • 19
  • I would advice you checking this question: ["What is the correct way to share the result of an Angular Http network call in RxJs 5?"](https://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-http-network-call-in-r) – kos Apr 23 '19 at 10:26
  • You could use a ReplaySubject to cache the data and on subsequent calls to the resolver return the ReplaySubject. – Paul A. Trzyna Apr 23 '19 at 17:56

1 Answers1

0

you need return of(this.result) -your function alwasys need return an observable. So

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    if (this.result)
       return of(this.result)

    return this.httpClient.get<Array<string>>('<api_route>')
            .pipe(
                tap(fields => {
                    this.result= fields;
                })
      }
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • 1
    IMK, This isn't really necessary. A resolver can very well return a normal data as well as an Observable – Ashish Ranjan Apr 23 '19 at 09:28
  • According to the resolve interface, both solutions are possible. But that doesn't really solve the problem of having to manually manage caching – dc-p8 Apr 23 '19 at 09:45
  • ::glups:: Sorry, I thinked that was a simple method of the service – Eliseo Apr 23 '19 at 09:53