我的流程类似-父组件具有三个子组件。子级的所有功能都来自父级组件的ngOnInit。所有孩子的工作都是在父母的基础上进行的。子组件在父组件的ngOnInit()上工作。当我导航到子组件时,将运行子组件的ngOnInit(),然后运行父组件的ngOnInit()。 现在,我希望在父组件中定义的函数在父组件内部时不起作用,但是当它转到子组件时,它应该起作用。而且我们不能分离该功能并将其仅放在子级中(这可能是一个解决方案)。
因此,我们决定如何使用上述用例的方法是使用Service SharedComponent,该服务有助于我全局定义变量。
代码-
facility-definition.service.ts
import { Injectable, OnInit } from '@angular/core';
export interface SharedModel {
factorFlag:boolean
}
@Injectable({
providedIn: 'root'
})
export class FacilityDefinitionService {
SharedComponent: SharedModel = {
factorFlag:false
}
}
parent.component.ts
export class WorkOrderLimitComponent implements OnInit {
shareData;
constructor( private _woFaclityService: FacilityDefinitionService){
this.shareData = _woFaclityService.SharedComponent;
}
ngOnInit(){
addSubscribers() {
//code
if(!this.shareData.factorFlag == true){
//code
});
//code
}
}
child.component.ts
export class FactorFormComponent implements OnInit {
ngOnInit() {
this.shareData.factorFlag = true;
}
}
但是使用此全局变量factorFlag,最初它是Service.ts中定义的false,而当您输入父组件时,它又是false。现在,当您转到子组件时,全局变量factorflag在全局范围内变为true,因此父组件的addSubscribers()中的代码变为true并运行。现在,您再次回到父组件,factorflag保持为true,因此父组件内部的函数运行。我们不能在父组件的ngOnInit()中使factorflag = false,因为当您转到子组件时,先运行子组件ngOnInit(),然后运行父组件ngOnInit()。
请帮助解决问题。我们希望addSubscribers()仅在子级而不在父级中运行