将 toastr 与 angular2 一起使用

Use toastr with angular2

我正在使用这个节点包link

按照说明,打字稿编译器就不用理会了。 我认为问题与 here 描述的相同,但我找不到解决方法。

有什么帮助吗?

非常感谢

您只需添加<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>

toastr - plunker

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app', 
    template: `
      <button (click)="displayToastr()">Display Toastr</button>
    `
})
export class AppComponent {
  displayToastr() {
    toastr.info('I am here for few seconds');
  }
}

这意味着您可以直接使用 toastr 对象而无需像这样导入它:import * as toastr from '...';.

也就是说为了避免编译错误,你需要包含相应的类型:

/// <reference path="./toaster.d.ts" />

在组件中使用Toastr的方法如下:

/// <reference path="./toaster.d.ts" />

import {Component} from 'angular2/core';

@Component({
  selector: 'my-app', 
  template: `
    <div (click)="displayToastr()">Display Toastr</div>
  `
})
export class AppComponent {
  constructor() {
    toastr.options = { positionClass: 'toast-bottom-right' };
  }

  displayToastr() {
    toastr.info('message');
  }
}

这里是对应的plunkr:https://plnkr.co/edit/wzdoisKBrZYTeSX8r7Nd?p=preview.

  1. 在您的任意文件夹下创建一个 Toaster 服务 应用程序(最好是通用的)并在其中添加以下代码

    import { OpaqueToken } from '@angular/core'
    export let Toaster_Token = new OpaqueToken('toastr');
    
  2. 将其导入您的 App 模块,如下所示

    import { Toaster_Token } from './ToasterService';
    
  3. 声明一个引用了toastr.js的window.toastr的变量为

    declare let toastr : any; 
    
  4. 将以下代码添加到 providers 数组中

    { provide : Toaster_Token , useValue : toastr } 
    
  5. 在您的组件中,从 angular/core 导入 ToasterService 并注入,如下所示

    import { Toaster_Token } from './ToasterService';
    import { Inject} from '@angular/core';
    
  6. 您的构造函数已作为

    注入此服务
    constructor(@Inject( Toaster_Token ) private _toasterService : any){
    
    }
    
  7. 将烤面包机方法用作

    this._toasterService.success('This works');
    

LIVE DEMO

如果你使用 angular2-toaster (npm install angular2-toaster)

在html

<button class='btn btn-bar btn-warn' (click)='testToaster()'>testToaster</button>

在component.js

import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { ToasterModule, ToasterService, BodyOutputType } from "angular2-toaster";

@NgModule({
    imports: [ BrowserAnimationsModule, ToasterModule],
})

export class Democlass extends BaseComponent implements OnInit {
    constructor(...,
    private toasterService: ToasterService) {
. . .}

    public testToaster() {
    this.toasterService.pop("info", "Args Title info", "Args Body <p/>  sdf")
       .bodyOutputType = BodyOutputType.TrustedHtml;
}

您还可以使用其他 toast 属性作为

   let toast = this.toasterService.pop("info", "demo Title info", "demo Body <p/>  sdf");
   toast.bodyOutputType = BodyOutputType.TrustedHtml;        
   // these will be used
   toast.title = "Actual tite";
   toast.body = "new html body <i>italic</i><hr/>notes";
   // toast.clickHandler = ...
   // toast.type = "error";
   // toast.timeout = 20;
   // ...