Bruno A
Bruno A

Reputation: 127

Returning Observable from function

I have the following function in typescript:

getConfigurations() {
    let sessionConfig = sessionStorage.getItem('config');
    if(config)
        return of(sessionConfig);
    else {
        this.dataService.getRoute('configurations').subscribe(
        route => this.http.get<any[]>(route.ToString()).subscribe(
            result => {
                sessionStorage.setItem('config', result);
                return of(result);
            },
            error => {
                alert(error);
            }),
        error => {
            alert(error);
        }
        );
    }
}

The function should return a string if the sessionStorage key is already existent or use dataService to retrieve the value from back end and then set the value in the session. I'd like to return the value set in sessionStorage too (result), but I couldn't find a way to do it.

The function getRoute from dataService is:

getRoute(service: string){
    return this.http.get('urlToMyBackendWebApi');
}

Where http is the Angular HttpClient.

How could I get the value returned from getConfigurations() ?

I tried to subscribe to getConfigurations. I have no problems with the if condition (the string sessionConfig is returned) but how to get the result from the else condition? Should I return an observable of the entire part? In this case, how could I read the return?

Upvotes: 0

Views: 992

Answers (1)

Guerric P
Guerric P

Reputation: 31815

Don't subscribe to the observable, return it, and use the tap operator to store the response:

getConfigurations() {
    let sessionConfig = sessionStorage.getItem('config');
    if(config)
        return of(sessionConfig);
    else {
        return this.dataService.getRoute('configurations').pipe(
          mergeMap(route => this.http.get<any[]>(route.ToString()),
          tap(result => sessionStorage.setItem('config', result))
        );
    }
}

Upvotes: 4

Related Questions