【发布时间】:2020-12-21 15:41:49
【问题描述】:
我有一个简单的设置,其中配方项目可以触发带有配方项目数据的模式组件的显示。 这是代码。
// 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() {}
}
// recipe-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);
}
}
//recipe-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 链接,如果您想查看项目结构。
【问题讨论】:
标签: angular bootstrap-4 service rxjs bootstrap-modal