rashadb rashadb - 3 days ago 5
AngularJS Question

Ionic/Angular 2 Dependency Injection Not Working According to Pattern

I'm following the dependency injection pattern from: http://devdocs.io/angular~2_typescript/cookbook/dependency-injection

My code looks like this:

MyService.ts

import { Injectable } from '@angular/core';

@Injectable()
export class MyService {}


app.component.ts

import { Component, ViewChild } from '@angular/core';
import { MyService } from '../services/MyService';

@Component({
templateUrl: 'app.html',
providers: [MyService]
})

export class MyApp {}


MyComponent.ts

import { Component } from '@angular/core';

@Component({
selector: 'theComponent',
templateUrl: 'theComponent.html'
})
export class thisComponent {
constructor(private thisService: MyService) {}


I get the following error: Cannot find name 'MyService'.

I already checked to make sure that
"emitDecoratorMetadata": true

I've also tried the public, private and left off the extra discriptor public/private and I get the same error each time.

Answer

importing into your class files allows you to use the exported definitions from another file/module. You need to import the class into every file that uses that class definition.

So in thisComponent.ts, you'll need to include

import { MyService } from './path/to/services/MyService';

See https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#11.3.2 for more info on what this is doing in Typescript

This is different from the import properties of Modules in Angular2, which are about dependency chains and injectors.

Comments