Merge pull request #2566 from storybooks/fix-di

[app:angular] Fixed dependency injection for components
This commit is contained in:
Igor 2017-12-28 13:39:05 +02:00 committed by GitHub
commit 75811b52f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 76 additions and 2 deletions

View File

@ -1,5 +1,9 @@
/* eslint-disable no-param-reassign */
/* globals window */
import { ɵReflectionCapabilities } from '@angular/core';
// eslint-disable-next-line new-cap
const reflectionCapabilities = new ɵReflectionCapabilities();
function getMeta(component, [name1, name2], defaultValue) {
if (!name2) {
@ -27,5 +31,11 @@ export function getPropMetadata(component) {
}
export function getParameters(component) {
return getMeta(component, ['parameters'], []);
const params = reflectionCapabilities.parameters(component);
if (!params || !params[0]) {
return getMeta(component, ['parameters'], []);
}
return params;
}

View File

@ -1,3 +1,7 @@
import { ɵReflectionCapabilities } from '@angular/core';
const reflectionCapabilities = new ɵReflectionCapabilities();
function getMeta(component: any, [name1, name2]: any, defaultValue: any) {
if (!name2) {
name2 = name1;
@ -24,5 +28,11 @@ export function getPropMetadata(component: any) {
}
export function getParameters(component: any) {
return getMeta(component, ['parameters'], []);
const params = reflectionCapabilities.parameters(component);
if (!params || !params[0]) {
return getMeta(component, ['parameters'], []);
}
return params;
}

View File

@ -0,0 +1,7 @@
<div>
<div>All dependencies are defined: {{isAllDeps()}}</div>
<div>Title: {{title}}</div>
<div>Injector: {{injector.constructor.toString()}}</div>
<div>ElementRef: {{elRefStr()}}</div>
<div>TestToken: {{testToken}}</div>
</div>

View File

@ -0,0 +1,19 @@
import { storiesOf } from '@storybook/angular';
import { withKnobs, text } from '@storybook/addon-knobs/angular';
import { DiComponent } from './di.component';
storiesOf('Component dependencies', module)
.add('inputs and inject dependencies', () => ({
component: DiComponent,
props: {
title: 'Component dependencies'
}
}))
.addDecorator(withKnobs)
.add('inputs and inject dependencies with knobs', () => ({
component: DiComponent,
props: {
title: text('title', 'Component dependencies')
}
}));

View File

@ -0,0 +1,28 @@
import { Component, Input, InjectionToken, Injector, ElementRef, Inject } from '@angular/core';
export const TEST_TOKEN = new InjectionToken<string>('test');
@Component({
selector: 'di-component',
templateUrl: './di.component.html',
providers: [
{ provide: TEST_TOKEN, useValue: 123}
]
})
export class DiComponent {
@Input() title: string;
constructor(
protected injector: Injector,
protected elRef: ElementRef,
@Inject(TEST_TOKEN) protected testToken: number
) {}
isAllDeps(): boolean {
return Boolean(this.testToken && this.elRef && this.injector && this.title);
}
elRefStr(): string {
return JSON.stringify(this.elRef);
}
}