angularprimengangular19

Primeng Toast not working in Angular auth guard function


I tried to display toast in CanActivateFn function, but it didn't work and the browser console display this error.

ERROR NullInjectorError: NullInjectorError: No provider for _MessageService!
    at NullInjector.get (core.mjs:1644:21)
    at R3Injector.get (core.mjs:2169:27)
    at R3Injector.get (core.mjs:2169:27)
    at injectInjectorOnly (core.mjs:1100:36)
    at ɵɵinject (core.mjs:1106:40)
    at inject (core.mjs:1191:10)
    at authGuard (auth.guard.ts:8:26)

Here is my authGuard code:

import { CanActivateFn } from '@angular/router';
import { AccountService } from '../services/account.service';
import { inject } from '@angular/core';
import { MessageService } from 'primeng/api';

export const authGuard: CanActivateFn = (route, state) => {
  const accountService = inject(AccountService);
  const messageService = inject(MessageService);

  if(accountService.currentUser()) {
    return true;
  } else {
    messageService.add({
      severity: 'error',
      summary: 'Access Denied',
      detail: 'You need to be logged in to view this page.',
      life: 2000,
    });
    return false;
  }
};

I've already add MessageService as provider in app.component.ts.

import { MessageService } from 'primeng/api';
//...

@Component({
  selector: 'app-root',
  imports: [Toast],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  providers: [MessageService]
})
export class AppComponent implements OnInit {
//...

Am I missed something here?

I try to display the toast but run the code inside the authguard. The expected result is the toast should be displayed.


Solution

  • You need to add the provider MessageService in the application level.

    bootstrapApplication(App, {
      providers: [
        ...
        MessageService,
        ...
      ]
    });
    

    Or try providedIn: 'root' on the service, if the service is not provided from a library.

    @Injectable({ providedIn: 'root' })
    export class MessageService {
     ...