2016-11-16 76 views
1

我有一个CheckIn页面,它具有title属性。在Ionic 2中,如何在两个组件之间传递属性数据?

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> 

这给了我undefined当我console.log它。请协助。

+0

你的代码看起来不错。你想要什么'console.log'? 'this.tab3Root'? – Huiting

+0

@Huiting我只是想从我导入'CheckInPage'的地方访问'CheckInPage.title'属性:'TabsPage'。 –

+0

@KaMok,标签不能像那样工作。 'tabTitle'属性只能是一个字符串,所以你需要静态设置标题。你想稍后改变它,或者你为什么要尝试使用'title'属性? – sebaferreras

回答

1

有几种不同的方式来传递离子页面,这将在本视频之间的数据: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() { 
    } 

} 

在组件要使用请确保将其导入并将其注入到构造函数中:

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

} 

Hope这有帮助!

+0

自从我第一次打开这篇文章后,我已经在Ionic中获得了很多,我很早以前就已经找到了我的答案。不管怎么说,还是要谢谢你。 –

-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() { 

    } 
} 

你可以试试这个。

+0

我已经完成了。不起作用。你有这个工作成功吗? –

+0

我使用的是较早版本的Ionic('2.0.0-beta.4'),因此语法与新版本稍有不同。我的代码看起来与您发布的代码很相似。 – Huiting

+0

当你说它不工作,能够详细说明?该页面仅显示标签,但不显示正确的标签视图?或者根本没有显示任何标签 – Huiting

相关问题