http-get.pipe.ts

TypeScript source for Automatic loading spinners in Angular, 72 lines. Raw file

import { ChangeDetectorRef, OnDestroy, Optional, Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { LoadingManager } from './loading-manager';

//  'url' | httpGet fetches the URL and returns what it gets back, undefined until then, and tells the
//  nearest loader around it while it's loading
@Pipe({ name: 'httpGet', pure: false })
export class HttpGetPipe implements PipeTransform, OnDestroy {
    private url: string | undefined;
    private value: any;
    private subscription: Subscription | undefined;

    constructor(
        private http: HttpClient,
        private changeDetector: ChangeDetectorRef,
        @Optional() private manager: LoadingManager,
    ) {
        if (this.manager) {
            this.manager.register(this);
        }
    }

    transform(url: string | undefined): any {
        //  Called on every change detection, so only fetch when the URL changes
        if (url !== this.url) {
            this.url = url;
            this.load(url);
        }
        return this.value;
    }

    private load(url: string | undefined) {
        //  Cancel the last request, so an old response can't replace a newer one
        this.stop();
        if (url === undefined) {
            return;
        }
        this.setLoading(true);
        this.subscription = this.http.get(url).subscribe(
            (value) => {
                this.value = value;
                this.setLoading(false);
                this.changeDetector.markForCheck();
            },
            () => {
                this.setLoading(false);
            },
        );
    }

    private setLoading(loading: boolean) {
        if (this.manager) {
            this.manager.setLoading(this, loading);
        }
    }

    private stop() {
        if (this.subscription !== undefined) {
            this.subscription.unsubscribe();
            this.subscription = undefined;
            this.setLoading(false);
        }
    }

    ngOnDestroy() {
        this.stop();
        if (this.manager) {
            this.manager.unregister(this);
        }
    }
}