通过拦截器触发angular2-notifications

时间:2018-06-05 08:13:01

标签: angular

我的角度项目中有一个拦截器代码,它显示了api响应的警报,我想用angular2-notifications替换它。

app.component.html

<router-outlet><app-spinner></app-spinner></router-outlet>

app.interceptor.ts

import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Injectable, Output, EventEmitter } from '@angular/core';
import { Router } from "@angular/router";
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';


@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private router: Router) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const loaderContainer = document.getElementById("page-loader");
        if (sessionStorage.getItem('token')) {
            loaderContainer.style.display = "block";
            // Clone the request to add the new header
            const clonedRequest = req.clone({ headers: req.headers.set('Authorization', sessionStorage.getItem('token')) });
            // Pass the cloned request instead of the original request to the next handle
            return next.handle(clonedRequest).do(event => {

                // if the event is for http response
                if (event instanceof HttpResponse) {
                    loaderContainer.style.display = "none";
                    // stop our loader here
                    //this._loadingBar.complete();
                }

            }, err => {
                if (err instanceof HttpErrorResponse) {
                    loaderContainer.style.display = "none";
                }
                if (err instanceof HttpErrorResponse && (err.status == 401 || err.status == 403)) {
                    sessionStorage.clear();
                    this.router.navigate(['auth/login/simple']);
                    alert("sorry your session expire please logn to continue")
                }
            });
        }
        return next.handle(req);
    }
}

如何更换&#34;提醒(&#34;抱歉您的会话过期请登录以继续&#34;)&#34;与angular2通知烤面包机?

我无法弄清楚在哪里

<simple-notifications [options]="options"></simple-notifications>

在哪个文件中以及如何通过拦截器触发它?

1 个答案:

答案 0 :(得分:0)

您可以将<simple-notifications [options]="options"></simple-notifications>放入主要组件html。

你必须导入 NotificationsService 并将其注入拦截器的构造函数

import { NotificationsService } from 'angular2-notifications';

constructor(
          private router: Router,
          private notificationsService: NotificationsService
        ) {}

然后,在intercept方法中,您可以使用通知服务创建通知。

`this._notifications.create(title, content, type, temp);`

查找angular2-notifications

的官方演示