Primeng Toast 在 Angular 身份验证保护功能中不起作用

问题描述 投票:0回答:1

我尝试在 CanActivateFn 函数中显示 toast,但它不起作用,并且浏览器控制台显示此错误。

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)

这是我的 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;
  }
};

我已经在 app.component.ts 中添加 MessageService 作为提供者。

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 {
//...

我在这里错过了什么吗?

我尝试显示 toast,但在 authguard 内运行代码。预期的结果是应该显示 toast。

angular primeng angular19
1个回答
0
投票

您需要在应用程序级别添加提供商

MessageService

bootstrapApplication(App, {
  providers: [
    ...
    MessageService,
    ...
  ]
});
© www.soinside.com 2019 - 2024. All rights reserved.