简体   繁体   中英

Angular2: Injecting a provider into a component using a custom decorator or annotation?

I'm hiding tabs in Ionic 2 for certain @Page s (an Ionic 2 decorator) using a simple TabsProvider :

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

The tabs component subscribes to currentState , and TabsProvider is injected into various pages as below:

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

This code is practically all boilerplate, and would be much cleaner if I could define this functionality in a decorator (or annotation), eg:

import { Page } from 'ionic-angular';
import { hideTabs } from './tabs';

@hideTabs()
@Page({
  ...
})
export class BuyPage {
}

But I'm having trouble determining how to inject TabsProvider and add the onPageWillEnter and onPageWillLeave methods to SamplePage.

Can a decorator (or annotation) somehow inject additional Angular providers?

The farthest I've gotten so far:

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

This gets us part of what we're looking for, but it's still necessary to import and inject TabsProvider as a specific instance member:

sample-page.ts

import {Page, Events} from 'ionic-angular';
import { hideTabs, TabsProvider } from './tabs';

@hideTabs()
@Page({
  ...
})
export class SamplePage {
  constructor(public tabsProvider: TabsProvider) {
  }
}

Is it possible to fully abstract this into @hideTabs() ?

Edit:

Relevant parts of the tabs component (for anyone interested in implementing) 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;
}

I have just had the same problem, and this is the solution I came up with. The general approach is to:

  • Use Reflect.getOwnMetadata to read the existing dependencies from the class.
  • Add to the list of dependencies
  • Create a new constructor which wraps the old constructor and deals with these dependencies.

tabs.ts :

    import TabsProvider from "./tabs";

    export function hideTabs() {
      return function(cls: Function) : any {

        // Save existing onPageWillEnter and onPageWillLeave inplementations
        let enter = cls.prototype.onPageWillEnter || function () {};
        let leave = cls.prototype.onPageWillLeave || function () {};

        // Create new constructor for class
        const newCls = function (tabsProvider, ...args) {
            this.__hideTabs__tabsProvider = tabsProvider;
            return cls.apply(this, args);
        }

        // Copy prototype to new constructor
        newCls.prototype = constructor.prototype;

        // Copy metadata to new constructor
        let metadatakeys = Reflect.getMetadataKeys(cls);
        metadatakeys.forEach(function (key) {
          Reflect.defineMetadata(key, Reflect.getOwnMetadata(key, cls), newCls)
        });

        // Read dependencies list from 'cls', add our own dependency, and write list to 'newCls'
        let dependencies = Reflect.getOwnMetadata('design:paramtypes', cls);
        dependencies = [TabsProvider].concat(dependencies)
        Reflect.defineMetadata('design:paramtypes', params, newCls);

        // Define new onPageWillEnter and onPageWillLeave implementation which implement tab show/hide functionality
        // and also call the old implementation saved above (if they exist)
        newCls.prototype.onPageWillEnter = function() {
          this.tabsProvider.hideTabs();
          enter.apply(this, arguments);
        };

        newCls.prototype.onPageWillLeave = function() {
          this.tabsProvider.showTabs();
          leave.apply(this, arguments);
        };

        return newCls;
      }
    }

I would also recommend moving the @hideTabs decorator below the @Page decorator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM