【问题标题】:In Ionic 2, how to pass attribute data between two components?在 Ionic 2 中,如何在两个组件之间传递属性数据?
【发布时间】:2017-03-31 02:53:56
【问题描述】:

我有一个具有title 属性的CheckIn 页面。

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  templateUrl: 'check-in.html'
})
export class CheckInPage {

  public title: string = 'Check In';
  constructor(public navCtrl: NavController) {
  }
}

我将此页面导入我的TabsPage

import { Component } from '@angular/core';
import { CheckInPage } from '../check-in/check-in';

@Component({
  templateUrl: 'tabs.html',
})
export class TabsPage {

  public tab3Root: any;

  constructor() {
    this.tab3Root = CheckInPage;
  }
}

现在,我想在我的 TabsPage 视图中使用它:

<ion-tabs>
  <ion-tab [root]="tab3Root" tabTitle="{{tab3Root.title}}" tabIcon="cog"></ion-tab>
</ion-tabs>

当我console.log 时,这给了我undefined。请帮忙。

【问题讨论】:

  • 您的代码看起来不错。你想console.log 做什么? this.tab3Root?
  • @Huiting 我只是想从我导入CheckInPage 的位置访问CheckInPage.title 属性:TabsPage
  • @KaMok,标签不能那样工作。 tabTitle 属性只能是字符串,所以需要静态设置标题。您想稍后更改它还是为什么要尝试使用 title 属性?

标签: ionic-framework ionic2 ionic-view


【解决方案1】:

尝试将页面分配给构造函数之外的每个选项卡。 https://ionicframework.com/docs/v2/api/components/tabs/Tab/

html

<ion-tabs>
 <ion-tab [root]="chatRoot" tabTitle="Chat" tabIcon="chat"><ion-tab>
</ion-tabs>

js/ts

import { ChatPage } from '../chat/chat';

@Component({
  templateUrl: 'build/pages/tabs/tabs.html'
})

export class Tabs {
  // here we'll set the property of chatRoot to
  // the imported class of ChatPage
  chatRoot = ChatPage;

  constructor() {

  }
}

你可以试试这个。

【讨论】:

  • 我已经这样做了。不工作。你让这个工作成功了吗?
  • 我使用的是旧版本的 Ionic (2.0.0-beta.4),因此语法与新版本略有不同。我的代码与您发布的代码相似。
  • 当你说它不起作用时,能详细说明吗?页面是否仅显示选项卡而不显示正确的选项卡视图?或者根本没有显示标签
【解决方案2】:

在 Ionic 中,有几种不同的方法可以在页面之间传递数据,本视频介绍了这些方法:https://www.youtube.com/watch?v=T5iGAAypGBA

为简洁起见,我将在这里仅介绍其中一种方式:如果您希望在多个页面之间保留某些内容,则可以通过 Ionic 2 Provider 来实现。

您可以在 CLI 中生成提供程序:

ionic g provider DemoProvider

它将生成一个提供程序,您可以向其中添加变量,如下所示:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the DemoProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class DemoProvider {

  mySharedVariable: String = "Hello";

  constructor() {
  } 

}

在你想使用provider的组件中,确保你导入它,并注入到构造函数中:

import { Component } from '@angular/core';
import { DemoProvider } from '../../providers/demoProvider';

@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.html'
})
export class TabsPage {

  constructor(public demoProvider:DemoProvider) {

  }
  ionViewWillEnter(){
        console.log(demoProvider.mySharedVariable);
  }

}

希望有帮助!

【讨论】:

  • 自从我第一次打开这篇文章以来,我在 Ionic 上的进步好多了,而且我很久以前就找到了答案。还是谢谢。
猜你喜欢
  • 2018-02-22
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2017-07-19
  • 2019-09-25
相关资源
最近更新 更多