Angular 2 DI系统中 函数forwardRef 的作用?
生活随笔
收集整理的這篇文章主要介紹了
Angular 2 DI系统中 函数forwardRef 的作用?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先來看下面代碼
import {Component,Inject} from 'angular2/core'; @Component({selector: 'app',template: `<h1>test</h1>`, }) export class App {constructor(service:Service) {console.log(service);} }@Injectable() class Service { }bootstrap(App,[Service])如果運行代碼,會拋出一個錯誤
Cannot resolve all parameters for App(undefined). Make sure they all have valid type or annotations.
原因呢很簡單。class Service 在 class App的下面,所以在constructor(service:Service) Service是undefined,所以無法使用類型來注入,來看下編譯后的代碼
var App = (function () {function App(service) {console.log(service);}App = __decorate([core_1.Component({selector: 'app',template: "\n <h1>test</h1>\n ",}), __metadata('design:paramtypes', [Service])], App);return App;})();exports.App = App;var Service = (function () {function Service() {}Service = __decorate([core_2.Injectable(), __metadata('design:paramtypes', [])], Service);return Service;})();bootstrap(App,[Service])class 最終被編譯成 函數 并賦值給變量,變量不會被編譯器提升到最頂部,所以在App里的Service是undefined。最簡單的解決方案就是,改變順序
import {Component,Inject} from 'angular2/core'; @Injectable() class Service { } @Component({selector: 'app',template: `<h1>test</h1>`, }) export class App {constructor(service:Service) {console.log(service);} } bootstrap(App,[Service])當然,程序寫到后面可能越來越復雜,在最后合并的時候可能無法保證所有的順序,那么就可以通過forwardRef來解決這個問題
import {Component,Inject,forwardRef} from 'angular2/core'; @Component({selector: 'app',template: `<h1>test</h1>`, }) export class App {constructor(@Inject(forwardRef(() => Service)) service) {console.log(service);} }@Injectable() class Service {}bootstrap(App,[Service])總結
以上是生活随笔為你收集整理的Angular 2 DI系统中 函数forwardRef 的作用?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编写边界条件测试用例原则
- 下一篇: JS变量对象详解