其他组件的Angular2调用方法

标签 angular

我有一个 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/

相关文章:

angular - 如何在 Angular 中访问 ControlValueAccessor 的自定义实现中的 'updateOn' 选项?

angular - 以 Angular 4 显示一个 div 并隐藏另一个 div

javascript - Angular 8 : Trying to use form data to format a string in a service, 但页面不断重新加载,变量未重新分配表单值

javascript - ionic 2 中 Promise 函数内的 nav

angular - ionic CLI 启动 : starterkit v3?

angular - Visual Studio 2017 .NET Core 2.1 Angular 上出现 "npm run build -- --prod"错误

javascript - 如何在 Angular 2中将数据从父构造函数传递到子组件

html - 如何从 typescript 文件中以 Angular 获取背景颜色并将其绑定(bind)到我的 html 页面?

angular - Angular (@angular/localize)是否可以进行运行时语言翻译?

angular - 为 Angular 根组件/模块指定 @Input() 参数