【发布时间】:2016-07-27 16:03:13
【问题描述】:
我正在使用简单的TabsProvider 为某些@Pages(Ionic 2 装饰器)在 Ionic 2 中隐藏标签:
tabs.ts
import { Injectable } from 'angular2/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class TabsProvider {
currentState = new BehaviorSubject<boolean>(true);
public showTabs(){
this.currentState.next(true);
}
public hideTabs(){
this.currentState.next(false);
}
}
标签组件订阅currentState,TabsProvider被注入到各个页面如下:
sample-page.ts:
import {Page} from 'ionic-angular';
import { TabsProvider } from './tabs';
@Page({
...
})
export class SamplePage {
tabsProvider: TabsProvider;
constructor(tabsProvider: TabsProvider) {
this.tabsProvider = tabsProvider;
}
onPageWillEnter(){
this.tabsProvider.hideTabs();
}
onPageWillLeave(){
this.tabsProvider.showTabs();
}
}
这段代码几乎都是样板文件,如果我可以在装饰器(或注释)中定义这个功能会更简洁,例如:
import { Page } from 'ionic-angular';
import { hideTabs } from './tabs';
@hideTabs()
@Page({
...
})
export class BuyPage {
}
但我无法确定如何注入 TabsProvider 并将 onPageWillEnter 和 onPageWillLeave 方法添加到 SamplePage。
装饰器(或注释)能否以某种方式注入额外的 Angular 提供程序?
到目前为止我走的最远:
在tabs.ts:
export function hideTabs() {
return function(cls: any) {
cls.prototype.onPageWillEnter = function() {
this.tabsProvider.hideTabs();
};
cls.prototype.onPageWillLeave = function() {
this.tabsProvider.showTabs();
};
return cls;
}
}
这让我们得到了我们正在寻找的一部分,但仍然需要导入和注入 TabsProvider 作为特定实例成员:
sample-page.ts
import {Page, Events} from 'ionic-angular';
import { hideTabs, TabsProvider } from './tabs';
@hideTabs()
@Page({
...
})
export class SamplePage {
constructor(public tabsProvider: TabsProvider) {
}
}
是否可以将其完全抽象为@hideTabs()?
编辑:
标签组件的相关部分(适用于任何有兴趣实现的人)pages/tabs/tabs.ts:
import { Page } from 'ionic-angular';
import { TabsProvider } from './tabs';
@Page({
...
})
export class TabsPage {
...
currentState: boolean;
constructor(TabsProvider: TabsProvider) {
TabsProvider.currentState.subscribe((state: boolean) => {
this.currentState = state;
});
}
}
pages/tabs/tabs.html:
<div [ngClass]="{'hide-tabs': !currentState}">
<ion-tabs>
...
</ion-tabs>
</div>
pages/tabs/tabs.scss:
.hide-tabs ion-tabbar-section {
display: none;
}
【问题讨论】:
标签: angularjs typescript angular ionic2 angular2-services