ng-bootstrap 更改路线后多次模态堆叠

ng-bootstrap modal stacking multiple times after changing route

我有一个简单的设置,其中配方项可以触发带有配方项数据的模态组件的显示。 这是代码。

// modal.service.ts

import { RecipeModel } from './recipe.model'
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class ModalService {
    selectedRecipe = new Subject<RecipeModel>();
    constructor() {}
}

// 食谱-item.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RecipeModel } from '../../recipe.model';
import { ModalService } from '../../modal.service';

@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html',
  styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
  isFavourite: boolean = false;
  @Input() recipeInstance: RecipeModel;
  cardText: string;
  constructor(private modalService: ModalService) { }

  ngOnInit(): void {
    this.cardText = this.recipeInstance.ingredients.slice(0, 3).map(elem => elem.name).join(', ');
    this.cardText = this.cardText + '...and ' + (this.recipeInstance.ingredients.length - 3) + ' more';
  }

  showRecipeDetail() {
    this.modalService.selectedRecipe.next(this.recipeInstance);
  }
}

// 食谱-detail.component.ts

import { Component, OnInit, Input, ViewChild } from '@angular/core';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; 
import { RecipeModel } from '../recipe.model';
import { ModalService } from '../modal.service';

@Component({
  selector: 'app-recipe-detail',
  templateUrl: './recipe-detail.component.html',
  styleUrls: ['./recipe-detail.component.css']
})
export class RecipeDetailComponent implements OnInit {
  @Input() selectedRecipe: RecipeModel;
  @ViewChild('mymodal') modal: any;
  
  constructor(private ngModalService: NgbModal, private modalService: ModalService) {}

  ngOnInit(): void {
    this.modalService.selectedRecipe.subscribe(val => {
      this.selectedRecipe = val;
      if (val) {
        this.ngModalService.open(this.modal, {size: 'lg', scrollable: true});
      }
    })
  }
}

当我第一次访问 /recipes 时,我可以在此处显示的食谱项目卡上单击“阅读更多”,然后像往常一样只弹出一次食谱详细信息模式组件。 当我改变路线然后回来时,模态的数量会增加一倍,如果我再次选择路线则会增加三倍。发生这种情况是因为我在 ngOnInit() 中调用模态弹出窗口,每次重新初始化 /recipes 时都会调用它。

我该如何解决这个问题?

编辑:Here 是 Github link 如果你想看看项目结构。

发生的事情是,每次创建 RecipeDetailComponent 时,它都会调用 ngOnInit(),因此每次发生这种情况时您都在订阅回调。因此,您将以为该事件注册的 N 个回调结束。

更简单的解决方案是在每次销毁组件时取消订阅 ngOnDestroy()。 https://angular.io/api/core/OnDestroy

在这里找到更好的解释和另一种选择: