如何在 Angular 5 中使用 ngx-toastr 更改每个用例的特定 toast 的位置

onm*_*way 2 toastr angular-material angular

我一直在阅读有关 ngx-toastr ngx-toastr的实际站点以及 Stack Overflow 上的其他帖子,但找不到适合我的工作案例的明确解决方案。

我正在尝试更改toastr特定用例的位置。例子; 当它是一个错误时,toastr在顶部显示。

我有一个非常普通的设置。

在我的app.module.ts我有以下内容:

import { ToastrModule } from 'ngx-toastr';
Run Code Online (Sandbox Code Playgroud)

在我的进口中,app.module.ts我有:

imports: [
    BrowserModule,
    ToastrModule.forRoot({
      timeOut: 3500,
      positionClass: 'toast-bottom-center',
      preventDuplicates: true,
}),
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我toastr在我的 constructor :

constructor(private toastr: ToastrService) {}
Run Code Online (Sandbox Code Playgroud)

我使用toastr如下:

this.toastr.error('There was an error loading the Asset List!', 'Asset Register');
Run Code Online (Sandbox Code Playgroud)

根据我的设置,所有吐司都显示在'toast-bottom-center'. 如何修改此调用以在顶部显示吐司?

this.toastr.error('There was an error loading the Asset List!', 'Asset Register');
Run Code Online (Sandbox Code Playgroud)

小智 9

为此提供服务。

首先创建一个枚举

export enum ToasterPosition {
  topRight = 'toast-top-right',
  topLeft = 'toast-top-left',
  bottomRight = 'toast-bottom-right',
  bottomLeft= 'toast-bottom-left',
  // Other positions you would like
}
Run Code Online (Sandbox Code Playgroud)

现在创建您的服务

export class ToasterService {
  constructor(private toastr: ToastrService) {}

  public error(title: string, message: string, positionClass: ToasterPosition) {
    this.toastr.error(message, title, { positionClass });
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,您就不会错过定位,因为您必须提供枚举。


小智 7

error方法的第三个参数用于提供 toastr 消息的位置(除其他外)。

this.toastrService.error('There was an error loading the Asset List!', 'Asset Register');

this.toastrService.warning('Some warning message', 'some title', {
   positionClass: 'toast-bottom-right' 
});
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助。