首页 文章

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

提问于
浏览
24

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

6 回答

  • 17

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

    Angular 2 component interaction

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

    angular-2-sibling-component-communication

  • 11

    Using a service:

    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'}
        });
      }
    }
    
  • 0
    • @Input和@Output

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

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

    • 依赖注入

    您可以将数据存储在Service中,然后将Service注入到所需的组件中 . 例如示例中的“user.server.ts”:

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

  • 3
  • 11

    角度有 Events API,可以为您完成 .

    Click here for more details on Events.

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

    从'ionic-angular'导入;

    用法:

    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', '');
        }
    
      }
    
  • 0

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

    项目结构:

    HTML

    • index.html

    • my-tabs.html

    • my-pane.html

    JS

    • script.js

    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>
    

    my-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>
    

    my-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

    希望这可以帮助 :)

相关问题