Tentei exibir o toast na função CanActivateFn, mas não funcionou e o console do navegador exibiu este erro.
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)
Aqui está meu código authGuard:
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;
}
};
Já adicionei MessageService como provedor em 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 {
//...
Esqueci de alguma coisa aqui?
Tento exibir o toast, mas executo o código dentro do authguard. O resultado esperado é que o toast deve ser exibido.