如何在Angular中的组件之间进行通信?

时间:2015-05-28 08:50:08

标签: angular components

我正在开发一个Web应用程序项目,我正在尝试使用Angular,我遇到了组件通信的问题。例如,父组件如何与子组件交换数据,如何在兄弟组件之间进行通信。

8 个答案:

答案 0 :(得分:17)

如果您尝试从父组件与子组件进行通信,则在角度文档中使用带@Output的@Input和EventEmitters可以清楚地描述这一点。

Angular 2 component interaction

至于兄弟姐妹之间的沟通,我在一个类似的问题中发布了一个答案,可能有助于跨兄弟组件共享数据的问题。目前,我认为共享服务方法效率最高。

angular-2-sibling-component-communication

答案 1 :(得分:12)

使用服务:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class AppState {
  public _subject = new Subject<object>();
  public event = this._subject.asObservable();

  public publish(data: any) {
    this._subject.next(data);
  }
}

你可以像这样发布类似事件的消息:

export class AppComponent {
  constructor(
    public appState: AppState
  ) {
    appState.publish({data: 'some data'});
  }
}

您可以订阅这些活动:

export class HomeComponent {
  constructor(
    public appState: AppState
  ) {
    appState.event.subscribe((data) => {
      console.log(data); // {data: 'some data'}
    });
  }
}

答案 2 :(得分:11)

  1. @Input和@Output

    如果有多部分组件 您可以使用@Input和@Output来交换数据。 文件:https://angular.io/guide/component-interaction

    示例:https://angular.io/generated/live-examples/component-interaction/eplnkr.html

  2. 依赖注入

    您可以将数据存储在Service中,然后将Service注入到您想要的组件中。例如&#34; user.server.ts&#34;在示例中:

    https://angular.io/generated/live-examples/dependency-injection/eplnkr.html

答案 3 :(得分:3)

答案 4 :(得分:0)

有角度的事件 API,可以为您完成。

Click here for more details on Events.

以下是我目前在项目中使用的一个简单示例。希望它可以帮助有需要的人。

  

从'ionic-angular'导入{Events};

用法:

  constructor(public events: Events) {
        /*=========================================================
        =  Keep this block in any component you want to receive event response to            =
        ==========================================================*/
        // Event Handlers
        events.subscribe('menu:opened', () => {
            // your action here
            console.log('menu:opened');
        });
        events.subscribe('menu:closed', () => {
            // your action here
            console.log('menu:closed');
        });
    }

    /*=====================================================
    = Call these on respective events - I used them for Menu open/Close          =
    ======================================================*/

    menuClosed() {
        // Event Invoke
        this.events.publish('menu:closed', '');
    }
    menuOpened() {
        // Event Invoke
        this.events.publish('menu:opened', '');
    }

  }

答案 5 :(得分:0)

可以在AngularJS中实现组件间通信。在AngularJS中,我们有一些名为 require 的属性,需要在组件中进行映射。按照下面的示例,它将从组件 myPane 访问组件 myTabs addPane(参数): -

项目结构:

HTML

  1. 的index.html
  2. MY-tabs.html
  3. MY-pane.html
  4. JS

    1. 的script.js
    2. <强>的script.js

      angular.module('docsTabsExample', [])
          .component('myTabs', {
            transclude: true,
            controller: function MyTabsController() {
              var panes = this.panes = [];
              this.select = function(pane) {
                angular.forEach(panes, function(pane) {
                  pane.selected = false;
                });
                pane.selected = true;
              };
              this.addPane = function(pane) {
                if (panes.length === 0) {
                  this.select(pane);
                }
                panes.push(pane);
              };
            },
            templateUrl: 'my-tabs.html'
          })
          .component('myPane', {
            transclude: true,
            require: {          //This property will be used to map other component
              tabsCtrl: '^myTabs' // Add ^ symbol before the component name which you want to map.
            },
            bindings: {
              title: '@'
            },
            controller: function() {
              this.$onInit = function() {
                this.tabsCtrl.addPane(this);  //Calling the function addPane from other component.
                console.log(this);
              };
            },
            templateUrl: 'my-pane.html'
          });

      <强>的index.html

      <my-tabs>
        <my-pane title="Hello">
          <h4>Hello</h4>
          <p>Lorem ipsum dolor sit amet</p>
        </my-pane>
        <my-pane title="World">
          <h4>World</h4>
          <em>Mauris elementum elementum enim at suscipit.</em>
          <p><a href ng-click="i = i + 1">counter: {{i || 0}}</a></p>
        </my-pane>
      </my-tabs>

      我-tabs.html

      <div class="tabbable">
        <ul class="nav nav-tabs">
          <li ng-repeat="pane in $ctrl.panes" ng-class="{active:pane.selected}">
            <a href="" ng-click="$ctrl.select(pane)">{{pane.title}}</a>
          </li>
        </ul>
        <div class="tab-content" ng-transclude></div>
      </div>

      我-pane.html

      <div class="tab-pane" ng-show="$ctrl.selected" ng-transclude></div>

      代码段:https://plnkr.co/edit/diQjxq7D0xXTqPunBWVE?p=preview

      参考:https://docs.angularjs.org/guide/component#intercomponent-communication

      希望这会有所帮助:)

答案 6 :(得分:0)

using DataService stackbliz

sender.ts

import { Component } from '@angular/core';
import {dataService} from './dataservice.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  //name = 'Angular';
  constructor(private SVC: dataService ){

  }
  sender(){
    this.SVC.name="sender"
    console.log("sending this string:    "+this.SVC.name)
  }

}

dataservice.ts

   import { Injectable } from '@angular/core';

    @Injectable()
    export class dataService {
    name=""
      constructor() { }
    }

receiver.ts

import { Component, OnInit } from '@angular/core';
import {dataService} from '../dataservice.service';
@Component({
  selector: 'app-recieved',
  templateUrl: './recieved.component.html',
  styleUrls: ['./recieved.component.css']
})
export class RecievedComponent implements OnInit {
  constructor(private dataservice: dataService ){

  }
  ngOnInit() { 
  }
print(){
  console.log("recieved:    " +this.dataservice.name)
}
}

答案 7 :(得分:0)

通过使用以下任何一种方法,我们可以连接 2 个组件。

  1. 使用@input()
  2. 使用@output()
  3. 使用服务。
  4. 父组件调用 viewchild。
  5. 父级使用局部变量与子级交互。