单击项目菜单时,从当前组件(路由器插座)调用功能

时间:2017-11-14 14:42:37

标签: angular

我有一个带有菜单和路由器插座的应用程序,其中显示了不同的组件。所有这些组件都具有saveForm函数的表单。我想知道当我单击菜单项时,如何从当前组件调用saveForm函数。如果表格尚未保存,如何停止传播(或防止默认)。

app.component.html:

...
<app-navbar></app-navbar>
<router-outlet></router-outlet>
...

component1.component.ts:

...
saveForm() {

}

componentN.component.ts:

...
saveForm() {

}

1 个答案:

答案 0 :(得分:1)

我解决了。我创建了一个共享服务:

@Injectable()
export class MenuFormService {
    private menuFormAnounceClickSubject = new Subject();
    private menuFormConfirmationSavedSubject = new Subject<boolean>();

    menuFormAnounceClick$ = this.menuFormAnounceClickSubject.asObservable();
    menuFormConfirmationSaved$ = this.menuFormConfirmationSavedSubject.asObservable();

    anounceClickMenuForm() {
        this.menuFormAnounceClickSubject.next();
    }

    confirmSaveMenuForm(saved: boolean) {
        this.menuFormConfirmationSavedSubject.next(saved);
    }
}

在菜单组件中:

export class MenuComponent implements OnInit {
    currentRouteItemMenu: string;

    constructor(
        private menuFormService: MenuFormService,
        private router: Router
    ) {}

    ngOnInit(): void {
        this.menuFormService.menuFormConfirmationSaved$.subscribe(
            saved => {
                if (saved) {
                    this.router.navigate([this.rutaItemActual]);
                }
            });
    }

    onClick(currentRouteItemMenu: string): void {
        this.currentRouteItemMenu = currentRouteItemMenu;
        this.menuFormService.anounceClickMenuForm();
    }
}

在每个包含表单的组件中:

export class NComponent implements OnInit, OnDestroy {
    subscription: Subscription;

    constructor(
        private menuFormService: MenuFormService
    ) {}

    ngOnInit(): void {
        this.subscription = this.menuFormService.menuFormAnounceClick$.subscribe(
            response => {
                if (this.form.valid) {
                    this.menuFormService.confirmSaveMenuForm(true);
                } else {
                    this.menuFormService.confirmSaveMenuForm(false);
                }
        });

    ngOnDestroy(): void {
        this.subscription.unsubscribe();
    }
}