首页 > 解决方案 > 在 ionic 中的组件和页面之间共享数据

问题描述

您好我正在学习离子,我想将组件文件访问到主页,当我在主页中提到组件类链接时,只有第一页显示剩余页面没有进入页面。

如何解决这个问题或告诉我任何其他方法来解决这个问题?


组件模块.ts

import { NgModule } from '@angular/core';
import { ImageComponent } from './image/image';
import { IonicModule } from 'ionic-angular';
import { VideoComponent } from './video/video';
import { AudioComponent } from './audio/audio';
import { TextComponent } from './text/text';

@NgModule({
    declarations: [
        ImageComponent,
        VideoComponent,
        AudioComponent,
        TextComponent
    ],
    imports: [
        IonicModule
    ],
    exports: [
        ImageComponent,
        VideoComponent,
        AudioComponent,
        TextComponent
    ]
})
export class ComponentsModule { }

应用模块.ts

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    ComponentsModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    ActionSheet 

  ]
})

应用程序.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <ion-card>
    <ion-card-header>
      Image
    </ion-card-header>
    <ion-card-content>
      <image></image>
    </ion-card-content>
  </ion-card>


  <ion-card>
    <ion-card-header>
      video
    </ion-card-header>
    <ion-card-content>
      <video></video>
    </ion-card-content>
  </ion-card>

  <ion-card>
      <ion-card-header>
        Audio
      </ion-card-header>
        <ion-card-content>
        <audio></audio>
      </ion-card-content>
    </ion-card>

</ion-content>

标签: angularionic3

解决方案


我知道有两种方法可以实现通过组件传递数据。

1)使用服务(我更喜欢这个)

数据服务.ts

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

    @Injectable()
    export class dataService {
        data: string;

        setData(data) {
            this.data = data;
        }

        getData(){
           return this.data;
        }
    }

app.component.ts

import { Component } from '@angular/core';
import { dataService } from './server.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private dataService: dataService){}

  getData() {
      retrun this.dataService.getData();
  }

}

2) 使用导航控制器

 //When you are using the push to switch pages you pass the data to the otherpage
    this.navCtrl.push(HomePage, {
          data: user
    });

在您刚刚访问的页面(在此示例中为 HomePage)中,您可以像这样访问数据:

constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.user = navParams.get('data');
  }

推荐阅读