日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2025/3/18 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Angular 2 DI系统中 函数forwardRef 的作用? 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

首先來(lái)看下面代碼

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])

如果運(yùn)行代碼,會(huì)拋出一個(gè)錯(cuò)誤
Cannot resolve all parameters for App(undefined). Make sure they all have valid type or annotations.

原因呢很簡(jiǎn)單。class Service 在 class App的下面,所以在constructor(service:Service) Service是undefined,所以無(wú)法使用類型來(lái)注入,來(lái)看下編譯后的代碼

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 最終被編譯成 函數(shù) 并賦值給變量,變量不會(huì)被編譯器提升到最頂部,所以在App里的Service是undefined。最簡(jiǎn)單的解決方案就是,改變順序

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])

當(dāng)然,程序?qū)懙胶竺婵赡茉絹?lái)越復(fù)雜,在最后合并的時(shí)候可能無(wú)法保證所有的順序,那么就可以通過(guò)forwardRef來(lái)解決這個(gè)問(wèn)題

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])

總結(jié)

以上是生活随笔為你收集整理的Angular 2 DI系统中 函数forwardRef 的作用?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。