app.component.ts与另一个组件angular 2之间的通信

时间:2017-09-13 22:03:29

标签: angular ionic-framework ionic2 angular2-services

我是Angular 2的初学者,因为我想将我的应用从角度1移动到更高效的东西。我不明白如何在两个组件之间进行通信。我的情况是我认为特别,因为我想将 app.component.ts 中的一些数据发送到 home.ts 这两个类不在同一目录中

以下是我的应用的架构:

>src 
  > app
    - app.component.ts  //where the data are generated  - 2 lateral menus
    - app.html  //html associated to app.component.ts 
    - app.module.ts
    - app.scss
  > pages
    > home
      - home.html  //home page
      - home.ts
      - home.scss

首先在app.html文件中我有一个按钮:

<ion-menu [content]="content" side="left" id="menuParameter">
    <ion-header>
        <ion-toolbar color="default">
            <ion-title>Menu1</ion-title>
        </ion-toolbar>
    </ion-header>
    
    <ion-content>   

        <ion-list>            
            <ion-item>
                <ion-label>On/Off</ion-label>
                <!-- click here to switch on/off -->
                <ion-toggle color="danger" checked="false" [(ngModel)]="isToggled" (ionChange)="notify()"></ion-toggle>
            </ion-item>
        </ion-list>              
    </ion-content>
</ion-menu>

<ion-menu [content]="content" side="right" id="menuInformation">
    <ion-header>
        <ion-toolbar color="default">
            <ion-title>Menu2</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content>
    </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

单击此按钮时,我会捕获app.component.ts中的值:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';



@Component({
  templateUrl: 'app.html'
})
export class AppComponent {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      this.isToggled = false;

    
    });
  }

  public isToggled: boolean;
  
  public notify() {
    //i want to send this value to home.ts component !
    console.log("Toggled: "+ this.isToggled); 
  }


}

最后,我想尽可能在​​名为home.ts的组件中获取此值:

import { Component } from '@angular/core';
import { Logger } from '../../app/logger.service'


import { HttpClient } from '@angular/common/http';
import { NavController, NavParams, MenuController } from 'ionic-angular';
import {TranslateService} from '@ngx-translate/core';



@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

/**
 * Contain link with 
 */
export class HomePage {

  private logger:Logger = new Logger(this.constructor.name);



  constructor(public translate: TranslateService, public navCtrl: NavController,
    public navParams: NavParams, 
    public menu: MenuController, private httpClient:HttpClient) {
    this.logger.log("instantiating HomePage()");
    menu.enable(true);
    
    
    translate.setDefaultLang('en');
    translate.use('en');
  }



  openMenu(evt) {
    if(evt === "main"){
       this.menu.enable(true, 'menuParameter');
       this.menu.enable(false, 'menuInformation');
    }else{
       this.menu.enable(true, 'menuInformation');
       this.menu.enable(false, 'menuParameter');
    }
    this.menu.toggle();
}

//method to get the value catched in app.component.ts that is to say the button value (true or False)!


}

提前致谢

JP

2 个答案:

答案 0 :(得分:1)

为此使用离子事件api,它非常简单易用,您的应用程序组件将发布到主题,主组件将订阅该主题以检索您想要传递的数据。

更多详情here

答案 1 :(得分:0)

您可以在角度中使用事件API。 You can refer this link as well.

以下是我目前正在使用的示例。

  

从&ion; angular-angular&#39;;

导入{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', () => {
  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', '');
}
}