在离子中共享组件和页面之间的数据

时间:2018-05-17 15:16:41

标签: angular ionic3

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

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

  

componentmodule.ts

*
  

appmodule.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 { }
  

app.html

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

  ]
})

1 个答案:

答案 0 :(得分:1)

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

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

data.service.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)使用NavController

 //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');
  }