日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

Angular 2 DI系统中 函数forwardRef 的作用?

發布時間:2025/3/18 windows 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 的作用?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。