2016-11-16 81 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

相關問題