2017-08-09 77 views
1

在我们的应用程序,我用翻译管道和我存储在StorageProvider(LocalStorage)刊登更改子页面中的值后,我们如何从子页面访问app.component?

我的问题是离子的菜单(在app.html,app.component)所选择的语言时,我们不能转换到所选择的语言更改子页面中的值。我的app.html代码如下所示;

app.html

<ion-menu [content]="content">  
     <ion-content class="smrt-dark"> 
     <ion-list> 
      <button color="dark" menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)" style="height: 150%" [hidden]="!isAuthenticate(p.isAccess)"> 
      <i class="fa fa-{{p.icon}} {{p.color}} circle-i-mn smrt-{{p.color}}" aria-hidden="true" item-start></i> 
      {{p.title}} 
      </button> 
     </ion-list> 
     </ion-content> 
    </ion-menu> 
    <ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav> 

app.component.ts

export class MyApp { 
    @ViewChild(Nav) nav: Nav; 

    rootPage: any = LoginPage; 
    pages: Array<{ title: string, component: any, icon: string, color: string, isAccess: string }>; 
    LANGUAGE; 
    constructor(...) { 
    console.log('main'); 
    if (this.db._config.LANGUAGE === null){ 
     this.storage.get('language'). then((data) => { 
     this.LANGUAGE = data; 
     this.translateService.use(this.db._config.LANGUAGE); 

     // used for an example of ngFor and navigation 
     this.pages = [ 
      {title: translateService.instant('home'), component: HomePage, icon: 'home', color: '', isAccess: 'HOME_LIST'}, 
      {title: translateService.instant('notes'), component: ListNotePage, icon: 'book', color: 'note', isAccess: 'NOTE_LIST'}, 
      {title: translateService.instant('tasks'), component: ListTaskPage, icon: 'check', color: 'task', isAccess: 'ISSUE_LIST'} 
     ]; 
     }); 
    } 
    this.initializeApp(); 
    } 

    isAuthenticate(key: string){ 
    return this.auth.isAuthenticate(key); 
    } 


    initializeApp() 
    { 
    this.platform.ready().then(() => { 
     this.statusBar.styleDefault(); 
     this.splashScreen.hide(); 
    }); 

    } 

如果有任何可用的方法来访问app.component.ts属性,该解决方案对我来说也是可以接受的。

感谢您的解决方案。

回答

1

您可以使用依赖注入将父组件实例注入其子组件,就像可以注入任何其他类一样。你只需要导入它:

import { AppComponent } from '../app.component'; 

,然后在子组件的构造函数:

constructor(private appComponent: AppComponent ... //other stuff//){ 

然后,你将能够从子组件访问AppComponent任何可用的公共属性和方法。

this.appComponent.appComponentMethod(); 

this.appComponent.appComponentProperty = someNewValue; 

我经常这样做的列表,标签,卡片等部件组成,其中父是创造几乎相同的儿童N个。我将父实例注入到每一个孩子,然后创建父组件,如方法:

children: ChildComponent[]; 

addChild(child : ChildComponent) { 
    this.children.push(child); 
} 

,然后在子组件:

constructor(private parent: ParentComponent) {} 

ngOnInit() { 
    this.parent.addChild(this); 
} 

这样每个组件,父和孩子,可以访问彼此的公共方法和属性。我通常尽可能地从父组件中进行管理,并根据需要向下进行委派。

+0

此解决方案是否可用于离子?我尝试但不行。在构造函数中会出现一些错误,LoginPage:(?,[object Object]) –

+0

我不知道关于离子的任何内容,所以我不能确定 - 但是第二眼看来,这在Angular中也不起作用。我没有意识到,因为我输入它,但我不认为你可以通过依赖注入注入应用程序组件它是最根组件。你必须从app组件中至少有一个兄弟姐妹开始。不能说离子,但。 – diopside