1
我跟隨谷歌的angular2 quick start(這些例子沒有Github ?!)Angular:如何使用appInject注入服務到組件中?
一切工作順利,直到是時候注入服務。
這是我的代碼:
import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
class FriendsService {
names: Array<string>;
constructor(){
this.names = ['Aviad', 'Chen', 'Yarden'];
}
}
@Component({
selector: 'display',
appInjector: [FriendsService]
})
@View({
template:
<p>My name: {{ myName }}</p>
<p>Friends:<p>
<ul>
<li *ng-for="#name of names">
{{name}}
</li>
</ul>
,
directives: [NgFor]
})
export default class DisplayComponent {
myName: string;
names: Array<string>;
constructor(friendsService: FriendsService){
this.myName = 'Alice';
this.names = friendsService.names;
}
}
我遇到了很多例外情況,但第一個和我認爲是最相關的是:
可能相關EXCEPTION: No provider for FriendsService! (DisplayComponent -> FriendsService) angular2.dev.js:22367 STACKTRACE: angular2.dev.js:22367 Error: DI Exception
at NoBindingError.BaseException (angular2.dev.js:7735)
at NoBindingError.AbstractBindingError (angular2.dev.js:9029)
at new NoBindingError (angular2.dev.js:9052)
at Injector.execute._proto._throwOrNull (angular2.dev.js:27552)
at Injector.execute._proto._getByKeyDefault (angular2.dev.js:27597)
at Injector.execute._proto._getByKey (angular2.dev.js:27545)
at Injector.execute._proto._getByDependency (angular2.dev.js:27533)
at Injector.execute._proto._instantiate (angular2.dev.js:27430)
at Injector.execute._proto._new (angular2.dev.js:27403)
at InjectorInlineStrategy.execute.protoStrategy.instantiateBinding (angular2.dev.js:27192) angular2.dev.js:22367 ERROR CONTEXT:
一件事是<display>
組件是<my-app>
組件的指令:
import {Component, View, bootstrap} from 'angular2/angular2';
import DisplayComponent from './show-properties';
@Component({
selector: 'my-app'
})
@View({
template: '<display>',
directives: [DisplayComponent]
})
class AppComponent { }
bootstrap(AppComponent);
剛纔發佈了一個答案。我建議閱讀[changelog](https://github.com/angular/angular/blob/master/CHANGELOG.md)。 'appInjector'在'alpha-29'中被刪除,當前是'alpha-37'。正如你所看到的那樣,它們在文檔中被隱藏了)。 (開發人員都知道這一點,並正在努力改善現在) –
我期待他們相應地更新它;)但你是對的,謝謝你的提示 - 我一定會使用它現在。 – Shikloshi