Angular 2 - Dependency Injection and Barreling
<p>I've had a issue with Dependency Injection when importing a service from a barrel (<a href="https://angular.io/docs/ts/latest/glossary.html#!#barrel" rel="noreferrer">https://angular.io/docs/ts/latest/glossary.html#!#barrel</a>).</p>

<p>The issue I've faced is this:</p>

<p>Using the Angular guidelines, in the app there's a core barrel and then a barrel for every folder, these are achieved by having an index.ts in each folder. The core index.ts references everything from each folder and in turn each folder references the specific files.</p>

<p><strong>core index.ts</strong></p>

<pre><code>...
export * from './test/index';
</code></pre>

<p><strong>test index.ts</strong></p>

<pre><code>...
export * from './my-service.service';
</code></pre>

<p><strong>Code</strong></p>

<pre><code>import { MyService } from '../../core';
...

@Injectable()
export class AuthGuard implements CanActivate {
    isValidSession: boolean = false;
    errorMessage: any;

    constructor(
        private myService: MyService
    ) { }

    canActivate(
        // Not using but worth knowing about
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ) {
        return this.myService.doSomething();
    }
}
</code></pre>

<p>The above code resulted in the following error:</p>

<p><code>Uncaught Cannot resolve all parameters for 'AuthGuard'(undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthGuard' is decorated with Injectable.</code></p>

<p>Looking at the code I did not find any issue with missing <code>@Injectable</code> annotations. In fact the same service was being used in other components and was imported using the core index.ts.</p>

<p>An <a href="http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html" rel="noreferrer" title="Injecting services">article</a> I found suggested that <code>@Inject</code> in the constructor should be used because sometimes when TypeScript is converted to JavaScript the metadata is not created. This did not solve the issue in my case. After trying several things I simply tried changing the import to get the service like below, and the error was not thrown.</p>

<p><strong>Successful importation:</strong></p>

<pre><code>import { MyService } from '../../core/test/my-service.service';
</code></pre>

<p>or</p>

<pre><code>import { MyService } from '../../core/test';
</code></pre>

<p>I'm not sure if there's an issue in the index.ts files in my application or maybe the file structure itself is wrong, but from what I can see they're working fine. Would like to know why this particular <code>import</code> is making a difference.</p>