Ranjith Varatharajan
Ranjith Varatharajan

Reputation: 1694

Use ng2-toastr in a service

Scenario: I need to use ng2-toaster to display messages in all the components. Instead of writing the same toaster in every components. I need to write a component in a global service once and all the components make use of it. But I couldn't make it work. Any advice would be helpful. Thank you.

Here's my code:

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});
}

some.component.ts

import { GlobalService } from './services';
...
ngInit(){
   this.globalService.showSuccess()
}

Error:

this is the error i'm getting.

Error: Application root component cannot be found. Try accessing application reference in the later life cycle of angular app.

Upvotes: 2

Views: 2910

Answers (1)

ranakrunal9
ranakrunal9

Reputation: 13558

For Angular v2.2.x you need to add below in your Root component of your app :

// AppComponent.ts (Root component of your app)

constructor(public toastr: ToastsManager, vRef: ViewContainerRef) {
    this.toastr.setRootViewContainerRef(vRef);
}

Upvotes: 7

Related Questions