如何解决更改路径后多次进行ng-bootstrap模式堆叠
我有一个简单的设置,配方项可以触发带有配方项数据的模态组件的显示。 这是代码。
// 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() {}
}
//配方项目.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);
}
}
//配方细节.component.ts
import { Component,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链接,如果您想查看项目结构。
解决方法
发生的事情是,每次创建RecipeDetailComponent时,它都会调用ngOnInit(),因此,每次发生此事件时,您都在订阅回调。因此,您将为该事件注册N个回调。
更简单的解决方案是每次ngOnDestroy()销毁组件时退订。 https://angular.io/api/core/OnDestroy
在这里找到另一个选项的更好解释: Angular/RxJs When should I unsubscribe from `Subscription`
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。