找到你要的答案

Q:Dependency injection: Angular 2 not working

Q:依赖注入:角度2不工作

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.

我在angular.io教程显示数据。

我提出了一个新的类friendsservice分离关注的控制器逻辑和模型。我被使用依赖注入在displaycomponent类friendsservice类,依赖注入不工作。

控制台没有错误。页面不显示组件。这是导致组件不在页面上显示的行。

constructor(friendsService: FriendsService) 

页加载并显示组件(显示),如果将构造函数更改为:

constructor() 

我用angular2.alpha.34、Typescript、ES6。


我解决了。Eclipse Plugin引起了这个问题。插件不生成正确的代码ES5投诉。

我用“TSC看M T ES5 -- emitdecoratormetadata CommonJS APP。TS”命令在angular.io网站描述。

Eclipse插件生成的代码和命令“TSC”生成的代码稍有不同。

当使用“TSC”命令我实现预期的行为。

answer1: 回答1:

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.

首先,您必须在任何组件或指令之前定义服务。

如果你有这样的东西

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

class Service {
}

它会失败。在这种情况下你应该使用fordwardref或者你可以声明它之前你的成分。

class Service {
}

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

另一件事是,你必须将你的服务使用viewbindings(见componentannotation文档)。

class Service {
}

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

你是好去。我希望它帮助。

dependency-injection  typescript  angular2