简体   繁体   English

依赖注入:Angular 2无法正常工作

[英]Dependency injection: Angular 2 not working

I'm following the tutorials display-data in angular.io . 我关注angular.io中的教程display-data。

I introduced a new class FriendsService to separate the controller logic and model concern. 我引入了一个新类FriendsService来分离控制器逻辑和模型关注点。 I Called FriendsService class in DisplayComponent class by using dependency injection, the dependency injection not working. 我通过使用依赖项注入在DisplayComponent类中调用了FriendsService类,该依赖项注入不起作用。

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. 我正在使用angular2.alpha.34,Typescript,ES6。


I solved it. 我解决了 Eclipse-Plugin was causing the issue. Eclipse-Plugin引起了该问题。 The plugin wasn't generating the ES5 complaint correct code. 该插件未生成ES5投诉正确代码。

I used "tsc --watch -m commonjs -t es5 --emitDecoratorMetadata app.ts" command described in angular.io website. 我使用了angular.io网站中介绍的“ tsc --watch -m commonjs -t es5 --emitDecoratorMetadata app.ts”命令。

The eclipse-plugin generated code and the command "tsc" generated code is slightly different. eclipse-plugin生成的代码和命令“ tsc”生成的代码略有不同。

When using the "tsc" command I was achieving the expected behavior. 使用“ tsc”命令时,我达到了预期的行为。

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. 在这种情况下,您应该使用fordwardRef,或者可以在组件之前声明它。

class Service {
}

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

Another thing is that you have to inject your service using viewBindings (see ComponentAnnotation documentation). 另一件事是,您必须使用viewBindings注入服务(请参阅ComponentAnnotation文档)。

class Service {
}

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

And you are good to go. 而且你很好。 I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM