I want to use Interceptor in Angular that will display all the p-toast in angular, interceptor...

Discussão em 'Angular' iniciado por Hritik Khurana, Maio 17, 2025.

  1. I have used interceptor to show the toast errors or messages coming with the responses. Still the toast is not visible while I checked the interceptor is working fine. What is going wrong here?

    I am sharing the code snippets .

    Interceptor:

    import { Injectable } from '@angular/core';
    import {
    HttpInterceptor,
    HttpRequest,
    HttpHandler,
    HttpResponse,
    HttpErrorResponse,
    } from '@angular/common/http';
    import { MessageService } from 'primeng/api';
    import { Observable, throwError } from 'rxjs';
    import { catchError, tap } from 'rxjs/operators';

    @Injectable()
    export class HttpMessageInterceptorService implements HttpInterceptor {
    constructor(private messages: MessageService) {}

    intercept(
    req: HttpRequest<any>,
    next: HttpHandler
    ): Observable<any> {
    return next.handle(req).pipe(
    tap((event) => {
    if (event instanceof HttpResponse) {
    let messages: string[] = (event as HttpResponse<any>).body.messages;
    if (messages && messages.length) {
    messages.forEach((message) =>
    this.messages.add({
    severity: 'success',
    detail: message,
    life: 20000,
    })
    );
    }
    }
    }),
    catchError((err: any) => {
    if (err instanceof HttpErrorResponse) {
    let response = err as HttpErrorResponse;
    let errors: string[] = response.error?.messages;
    console.log("ege" , errors);
    if (errors && errors.length) {
    errors.forEach((error) =>
    this.messages.add({
    severity: 'error',
    detail: error,
    life: 20000,
    })
    );
    } else {
    this.messages.add({
    severity: 'error',
    detail: response.statusText,
    life: 20000,
    });
    }
    }
    return throwError(() => err);
    })
    );
    }
    }



    App.module.ts

    import {NgModule} from '@angular/core';
    import {BrowserModule} from '@angular/platform-browser';

    import {AppRoutingModule} from './app-routing.module';
    import {AppComponent} from './app.component';
    import {ToastModule} from "primeng/toast";
    import {RippleModule} from "primeng/ripple";
    import {InputTextModule} from "primeng/inputtext";
    import {FormsModule} from "@angular/forms";
    import {ButtonModule} from "primeng/button";
    import {AvatarModule} from "primeng/avatar";
    import {HttpClientModule , HTTP_INTERCEPTORS} from "@angular/common/http";
    import {MessageService} from "primeng/api";
    import {OverlayPanelModule} from "primeng/overlaypanel";
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { FriendComponent } from './friendship/friend/friend.component';
    import { TokenInterceptor } from './services/token.interceptor';
    import { TieredMenuModule } from 'primeng/tieredmenu';
    import { MenuModule } from 'primeng/menu';
    import { MenubarModule } from 'primeng/menubar';
    import { MessagesModule } from 'primeng/messages';
    import { HttpMessageInterceptorService } from './services/http-message-interceptor.service';
    @NgModule({
    declarations: [
    AppComponent,
    ],
    imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ToastModule,
    RippleModule,
    FormsModule,
    ButtonModule,
    AvatarModule,
    InputTextModule,
    OverlayPanelModule,
    BrowserAnimationsModule,
    TieredMenuModule,
    MenuModule,
    MessagesModule,
    MenubarModule

    ],
    providers: [
    MessageService, {
    provide: HTTP_INTERCEPTORS,
    useClass: HttpMessageInterceptorService,
    multi: true,
    },
    {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true,
    },

    ],
    bootstrap: [AppComponent]
    })
    export class AppModule { }


    I have used message service as providers, I have also defined interceptor in app module, I have also used p-toast in app.component.html. Still not visible.

    Tried this too

    export class HttpMessageInterceptorService implements HttpInterceptor {
    constructor(private messages: MessageService , private readonly changeDetectorRef : ChangeDetectorRef) {}

    intercept(
    req: HttpRequest<any>,
    next: HttpHandler
    ): Observable<any> {
    return next.handle(req).pipe(
    tap((event) => {
    if (event instanceof HttpResponse) {
    let messages: string[] = (event as HttpResponse<any>).body.messages;
    if (messages && messages.length) {
    messages.forEach((message) =>
    this.messages.add({
    severity: 'success',
    detail: message,
    life: 20000,
    })
    );
    }
    }
    }),
    catchError((err: any) => {
    if (err instanceof HttpErrorResponse) {
    let response = err as HttpErrorResponse;
    let errors: string[] = response.error?.messages;
    console.log("ege",errors); // even this is not printing on doing changes
    if (errors && errors.length) {
    errors.forEach((error) =>
    this.messages.add({
    severity: 'error',
    detail: error,
    life: 20000,
    })
    );
    } else {
    this.messages.add({
    severity: 'error',
    detail: response.statusText,
    life: 20000,
    });
    }
    }
    return throwError(() => err);
    }),
    finalize(()=> this.changeDetectorRef.detectChanges())
    );
    }
    }


    AppComponent.ts

    import {Component, OnInit , ViewChild } from '@angular/core';
    import {AuthService} from "./services/auth.service";
    import {UserProfileService} from "./services/user-profile.service";
    import {UserProfile} from "./models/userProfile";
    import { MessageService } from 'primeng/api';
    import { MenuItem } from 'primeng/api';
    import { TieredMenu } from 'primeng/tieredmenu';
    import { OverlayPanel } from 'primeng/overlaypanel';
    import { Router } from '@angular/router';
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    providers:[MessageService]
    })
    export class AppComponent implements OnInit{

    title = 'Outing';
    userProfile?: UserProfile;
    constructor(public route : Router,public authService:AuthService, private userProfileService:UserProfileService, public messageService: MessageService) {
    }

    ngOnInit() {
    this.userProfileService.getUserProfile().subscribe((userProfile)=>{
    this.userProfile=userProfile;
    });
    }

    signOutClicked($event: any) {
    $event.hide();
    this.userProfile = undefined;
    this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Signout Successfully!', sticky: true });
    setTimeout(() => {
    this.messageService.clear(); // Remove the toast manually
    }, 20000);
    this.authService.logOut();
    }
    @ViewChild('mobileMenu') mobileMenu!: OverlayPanel;

    menuItems: MenuItem[] = [
    { label: 'Home', icon: 'pi pi-home', routerLink: '/home', routerLinkActiveOptions: { exact: true, class: 'active' }},
    { label: 'Outings', icon: 'pi pi-map-marker', routerLink: '/outing' },
    { label: 'Friends', icon: 'pi pi-users', routerLink: '/friendship' },
    { label: 'Expenses', icon: 'pi pi-dollar', routerLink: '/expenses' },

    ];

    toggleMobileMenu(event: Event) {
    this.mobileMenu.toggle(event);
    }

    closeMobileMenu() {
    if (this.mobileMenu) {
    this.mobileMenu.hide();
    }
    }

    tier={
    'width':'8.5rem'
    }
    }

    Continue reading...

Compartilhe esta Página