导航到不同页面时 ng2-toastr 不工作

ng2-toastr not working when navigated to different page

我正在使用 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']);
}

你应该在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)

试试这个,

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。