rashadb rashadb - 1 year ago 76
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:


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

export class MyService {}


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

templateUrl: 'app.html',
providers: [MyService]

export class MyApp {}


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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download