在angular应用程序的根模块中导入要使用的ToastrModule,并在组件中导入ToastrService。
示例代码:
在app.module.ts文件中:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ToastrModule } from 'ngx-toastr'; // 导入ToastrModule
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, ToastrModule.forRoot() // 导入ToastrModule并调用forRoot方法 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
在要使用ToastrService的组件中:
import { Component } from '@angular/core'; import { ToastrService } from 'ngx-toastr'; // 导入ToastrService
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app';
constructor(private toastr: ToastrService) {} // 注入ToastrService
showSuccess() { this.toastr.success('Hello world!', 'Toastr fun!'); } }
在showSuccess方法中使用ToastrService的success方法来显示通知。