导航到不同页面时,ng2-toastr无法正常工作

时间:2018-04-02 07:18:34

标签: angular angular5 angular-router

我正在使用ng2-toastr来显示通知消息。当我在同一页面时工作正常,但当我导航到另一条路线时,它不会出现在新页面上

我在应用的主要组件

中设置ViewContainerRef的路线

app.component.ts

import { Component, ViewContainerRef } from '@angular/core';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  public viewContainerRef: ViewContainerRef;

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

sub component.ts

import { ToastsManager } from 'ng2-toastr/ng2-toastr';

 constructor(
    public toastr: ToastsManager,
    vcr: ViewContainerRef,
    private tripService: TripService) {
      this.toastr.setRootViewContainerRef(vcr);
 }

...
login() {
this.toastr.success('User Create Successfully !!..');
        this.router.navigate(['/login']);
}

2 个答案:

答案 0 :(得分:1)

试试这个,

app.component.ts

import { Component, ViewContainerRef } from '@angular/core';
import { ToastsManager } from 'ng2-toastr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  public viewContainerRef: ViewContainerRef;

  public constructor(public toastr: ToastsManager, viewContainerRef: ViewContainerRef) {
    this.viewContainerRef = viewContainerRef;

    this.toastr.setRootViewContainerRef(viewContainerRef);
  }
}

<强> sub.component.ts

import { ToastsManager } from 'ng2-toastr/ng2-toastr';

 constructor(
    public toastr: ToastsManager,
    private tripService: TripService) {
 }

...
login() {
this.toastr.success('User Create Successfully !!..');
        this.router.navigate(['/login']);
}

我希望这会对你有所帮助。您不需要在每个组件中导入ViewContainerRef。

答案 1 :(得分:0)

您应该在app.module.ts

中调出该模块

<强> TS

imports: [
//    
ToastModule.forRoot()
//
]

并在您需要使用的任何组件中调用TosterService。

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

this.ts.success(//MESSAGE);
this.ts.error(//MESSAGE)