我有一个 Angular2 应用程序,我在其中创建了一个 Header 组件,该组件在我的主 App 组件中呈现。
现在,我有另一个 Form 组件,它的提交按钮应该放在 Header 中。我怎么能那样做?
我有点需要在 Header 中的提交按钮和 Form 组件的提交方法之间进行通信。我知道进行父>子或子>父通信是微不足道的,但在这种情况下,我的 Header 和 Form 组件之间没有父子关系,也没有兄弟关系。
我的组件树是这样的:
- app-root
|-- app-header // -> this is where the submit button is
|-- app-edit-profile
|-- app-profile-form // -> this is my form
有人对可能的实现有任何想法吗?
最佳答案
您可以创建一个在您的 header 和表单组件之间共享的服务,您可以在其中定义 Observable
以便您可以从表单订阅该 Observable
并执行一些当您从 header 收到一些值时执行操作。
common.service.ts
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CommonService {
private notify = new Subject<any>();
/**
* Observable string streams
*/
notifyObservable$ = this.notify.asObservable();
constructor(){}
public notifyOther(data: any) {
if (data) {
this.notify.next(data);
}
}
}
header.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CommonService } from './common.service';
@Component({
selector : 'header',
templateUrl : './header.html'
})
export class HeaderComponent implements OnInit, OnDestroy {
constructor( private commonService: CommonService ){
}
ngOnInit() {
}
onSubmit(){
// this method needs to be called when user click on submit button from header
this.commonService.notifyOther({option: 'onSubmit', value: 'From header'});
}
}
form.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CommonService } from './common.service';
@Component({
selector : 'form',
templateUrl : './form.html'
})
export class FormComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor( private commonService: CommonService ){
}
ngOnInit() {
this.subscription = this.commonService.notifyObservable$.subscribe((res) => {
if (res.hasOwnProperty('option') && res.option === 'onSubmit') {
console.log(res.value);
// perform your other action from here
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
关于其他组件的Angular2调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40400062/