Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 {
 ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading