简体   繁体   中英

Dependency injection: Angular 2 not working

I'm following the tutorials display-data in angular.io .

I introduced a new class FriendsService to separate the controller logic and model concern. I Called FriendsService class in DisplayComponent class by using dependency injection, the dependency injection not working.

There's no errors in the console. The page doesn't display the component. This is the line causing the component not to display on the page.

constructor(friendsService: FriendsService) 

The page loads and displays the components (display) if change the constructor to:

constructor() 

I'm using angular2.alpha.34 , Typescript, ES6.


I solved it. Eclipse-Plugin was causing the issue. The plugin wasn't generating the ES5 complaint correct code.

I used "tsc --watch -m commonjs -t es5 --emitDecoratorMetadata app.ts" command described in angular.io website.

The eclipse-plugin generated code and the command "tsc" generated code is slightly different.

When using the "tsc" command I was achieving the expected behavior.

First you have to define the Service before that any component or directive.

If you have something like this

class Component {
    constructor(svc: Service) {
    }
}

class Service {
}

It will fail. In cases like this you should use fordwardRef or you just can declare it before your component.

class Service {
}

class Component {
    constructor(svc: Service) {
    }
}

Another thing is that you have to inject your service using viewBindings (see ComponentAnnotation documentation).

class Service {
}

@Component({
    viewBindings: [Service]
})
class Component {
    constructor(svc: Service) {
    }
}

And you are good to go. I hope it helps.

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