我一直在尝试将“toastr”添加到我的 Angular17 项目中,但将其注入到我的组件中不起作用。我使用 AngularCLI 添加了它。
我收到下一个错误:
错误错误[NullInjectorError]:R3InjectorError(独立[_PDSLoginComponent])[InjectionToken ToastConfig - > InjectionToken ToastConfig - > InjectionToken ToastCo nfig -> InjectionToken ToastConfig]: NullInjectorError:没有 InjectionToken ToastConfig 的提供者!
这是我的代码包含的内容:
import { Component, Output, EventEmitter, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { ToastrService, ToastNoAnimation } from 'ngx-toastr';
@Component({
selector: 'app-pdslogin',
standalone: true,
imports: [
FormsModule
],
providers: [
{ provide: ToastrService, useClass: ToastrService },
{ provide: ToastNoAnimation, useClass: ToastNoAnimation }
],
templateUrl: './pdslogin.component.html',
styleUrls: ['./pdslogin.component.css']
})
export class PDSLoginComponent {
loginData = {
UserId: ''
};
@Output() loginEvent = new EventEmitter();
onLogin() {
this.loginEvent.emit(this.loginData);
this.toastr.info("SHOWING TOASTR!!!","Info");
}
constructor(private router: Router, private toastr: ToastrService) { }
}
我尝试在 Stack Overflow 的论坛和问题中寻找解决方案,但所有这些都是针对以前版本的 Angular,现在 Angular17 使用“独立”属性,因此需要导入并注入正确的组件。
我们需要使用
provideToastr
和provideAnimations
将库的服务添加到environment providers
(如下所示的bootstrapApplication
对象的提供者数组),如文档中所述。
import { AppComponent } from './src/app.component';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideToastr } from 'ngx-toastr';
bootstrapApplication(AppComponent, {
providers: [
provideAnimations(), // required animations providers
provideToastr(), // Toastr providers
]
});
我们还可以删除独立组件中的
providers
数组值!
import { Component, Output, EventEmitter, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { ToastrService, ToastNoAnimation } from 'ngx-toastr';
@Component({
selector: 'app-pdslogin',
standalone: true,
imports: [
FormsModule
],
providers: [],
templateUrl: './pdslogin.component.html',
styleUrls: ['./pdslogin.component.css']
})
export class PDSLoginComponent {
loginData = {
UserId: ''
};
@Output() loginEvent = new EventEmitter();
onLogin() {
this.loginEvent.emit(this.loginData);
this.toastr.info("SHOWING TOASTR!!!","Info");
}
constructor(private router: Router, private toastr: ToastrService) { }
}
还需要在 angular.josn 文件上添加 css 路径
"styles": [ "src/styles.scss", "node_modules/ngx-toastr/toastr.css" ],