在服务中使用ng2-toastr

Ran*_*dan 2 typescript angular

场景:我需要用来ng2-toaster在所有组件中显示消息.而不是在每个组件中写相同的烤面包机.我需要在全局服务中编写一个组件,并且所有组件都使用它.但我无法使其发挥作用.任何意见将是有益的.谢谢.

这是我的代码:

global.service.ts

import { ToastsManager } from 'ng2-toastr/ng2-toastr';
'''
constructor(public toastr: ToastsManager) { }
...
showSuccess() {
  this.toastr.success('Called from Global service', 'Success!', {toastLife: 3000});
}
Run Code Online (Sandbox Code Playgroud)

some.component.ts

import { GlobalService } from './services';
...
ngInit(){
   this.globalService.showSuccess()
}
Run Code Online (Sandbox Code Playgroud)

错误:

这是我得到的错误.

Error: Application root component cannot be found. Try accessing application reference in the later life cycle of angular app.
Run Code Online (Sandbox Code Playgroud)

ran*_*al9 7

对于Angular v2.2.x,您需要在应用的根组件中添加以下内容:

// AppComponent.ts(应用的根组件)

constructor(public toastr: ToastsManager, vRef: ViewContainerRef) {
    this.toastr.setRootViewContainerRef(vRef);
}
Run Code Online (Sandbox Code Playgroud)