Retry HTTP request

Discussão em 'Angular' iniciado por AlexBor, Abril 23, 2025.

  1. AlexBor

    AlexBor Guest

    I have Angular service which is used in the Angular pipe. The job of that service is to do a HTTP request and fetch translations. Idea is to have a pipe which returns a Observable that only first subscriber will actually trigger HTTP request. And this is how subscription happens:

    {{( 'some_tag' | dynamicTranslation | async )}}


    This is pipe:

    @Pipe({ name: 'dynamicTranslation', standalone: true })
    export class DynamicTranslationPipe implements PipeTransform {
    constructor(private translationService: DynamicTranslationService) {}

    transform(tag: string): Observable<string> {
    return this.translationService.getTranslations()
    .pipe(
    map((translations: object) => {
    if (this.tagExistsInTranslations(translations, tag)) {
    return translations[tag] as string;
    }
    return tag;
    }),
    catchError(() => {
    return of(tag);
    })
    );
    }

    private tagExistsInTranslations(translations: object, tag: string): boolean {
    return Object.prototype.hasOwnProperty.call(translations, tag);
    }
    }



    And this is service:

    .
    .
    .

    protected _translations$: Observable<object>;
    private readonly _refreshTranslations$ = new BehaviorSubject<void>(undefined);

    public getTranslations(): Observable<object> {
    if(this._translations$) {
    return this._translations$;
    }

    this._translations$ = this._refreshTranslations$
    .pipe(
    tap(() => console.log('tap')),
    switchMap(() => this.requestTranslations()),
    shareReplay(1),
    retry()
    );

    return this._translations$;
    }

    public refreshTranslations(): void {
    this._refreshTranslations$.next();
    }


    So no matter how many subscriptions happen only one HTTP call is executed and this is what was intended. BUT, calling this.refreshTranslations() is not triggering another HTTP request? Why?

    Continue reading...

Compartilhe esta Página