karthikaruna
karthikaruna

Reputation: 3256

Notifying user when service returns, after routing to another component

I have a service that takes too long to return. Once the user has submitted a request, he/she should be able to navigate to any other page.

How can I alert her that the request she submitted has been processed (the service has returned), regardless of which page he/she is currently in?

Upvotes: 2

Views: 752

Answers (1)

Maciej Treder
Maciej Treder

Reputation: 12350

You have 2 options:

  1. You can create another component, let's say alertBox which would be added to your app skeleton:

<alert-box></alert-box>
<div class="main">
    <router-outlet></router-outlet>
</div>

Then you could have service:

export class MyService {
    private someObservable: BehaviorSubject<any> = new BehaviorSubject<any>();

    public makeSomeAction(): void {
        //some action
        this.someObservable.next('result');
    }

    public actionCompleted(): Observable<any> {
         return this.someObservable;
    }
}

injected into components:

@Component({})
export class ComponentOne {
    constructior(private _service: MyService) {}

    public someMethod() {
        this._service.makeSomeAction();
    }
}

@Component({})
export class AlertBox {
    constructior(private _service: MyService) {}

    public actionCompleted: void {
        this._service.actionCompleted.subscribe(() => console.log('action completed'));
    }
}

And you could handle your observables in this component.

  1. Another solution is using angular material. There is a snackbar component which fits your needs perfectly: https://material.angular.io/components/snack-bar/overview

Example usage:

import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';

@Injectable()
export class SnackBarService {

    constructor(private snackBar: MatSnackBar) {
    }

    public displayNotification(): void {
        const config: MatSnackBarConfig = new MatSnackBarConfig();
        config.duration = 1000; //time in ms

        this.snackBar.open("message", "action", config).afterDismissed().subscribe(() => {
             console.log('snackbar dismissed');
        });
    }
}

Upvotes: 2

Related Questions