2017-09-25 39 views
1

我想訪問和更改app.component.ts變量或訪問方法從其他頁面(otherpage.ts)或其他組件,如;如何從Ionic中的其他頁面訪問app.component變量和方法?

app.component.ts

@Component({ 
    templateUrl: 'app.html' 
}) 
export class MyApp { 

    accessedVariable: any; 

    constructor(){ } 

    accessedMethod() { 
    ..something 
    } 

} 

otherpage.ts

@Component({ 
    selector: 'page-other', 
    templateUrl: './otherpage.html', 
}) 
export class OtherPage { 

    constructor() { } 
} 
+0

是''OtherPage'的MyApp'一個孩子? – bazzells

+0

@ Dr.Geek你能簡單地解釋一下你正在嘗試做什麼,特別是那個accessibleMethod。此外,是app.component和otherpage父母相關或完全分開 – Mehdi

+0

也許這[回答](https://stackoverflow.com/a/44753236/4254681)會有所幫助。如果您只想更改子頁面中的菜單內容,只需使用[service](https://www.tutorialspoint.com/angular2/angular2_services.htm) – Duannx

回答

0

您可以通過多種方式做到這一點。

我可以告訴你的一種方法是使用Events

事件是一種發佈 - 訂閱式事件系統,用於發送和響應應用程序級別事件。

另一種方法,可以使用provider。對在使用的情況下,您可以通過provider分享您methodsvariables

+0

這不是我想要的。我想訪問app.component.ts意味着我想從子頁面或其他頁面更改某些變量。作爲''的一個例子,是否可以在更改子頁面的同時更改離子內容菜單... –

+0

您可以像'1st'方法中提到的那樣使用'Events'來完成。爲什麼你不能使用這種方法?根據您的使用情況,這是您唯一的選擇。 – Sampath

+0

因爲如果第一次加載項目,加載app.ccomponent(也是菜單項),並且在項目頁面發生更改後,我們無法更改現有app.component.ts中的參數... –

0

,最快的方式是使用GlobalVars提供者:

與第一安裝:

ionic g provider globalvars 

這將新的服務提供商自動添加到您的app.module.ts文件

import {Injectable} from '@angular/core'; 
@Injectable() 
export class GlobalVars { 
myGlobalVar: any; 
constructor() { 
this.myGlobalVar = ""; 
} 

setMyGlobalVar(value) { 
this.myGlobalVar = value; 
} 

getMyGlobalVar() { 
return this.myGlobalVar; 
} 
} 

您在那裏定義gettersetter方法和所需的變量可以通過這個類的實例訪問!在YourOtherPage.ts例如,您可以通過以下方式獲得變量:this.glVars.getMyGlobalVar()

在這裏你可以閱讀更多關於它:https://ionicallyspeaking.com/2016/03/10/global-variables-in-ionic-2/

+0

這不是我想要的。我想訪問app.component.ts! –

+0

我知道我也試過,但頁面是以Ionic/Angular封裝的。你可以試着用jQuery和你的index.html作爲替代來觸發你的頁面。我爲我的媒體數據庫做了這些 – Rebar

相關問題