修改 Angular Component 构造函数参数被认为是 breaking change
修改構造函數參數被認為是 breaking change:
Making any changes to the class constructor signature. Note that super calls need to be updated in classes extending ours.
如果我們在構造函數里引入新的參數,這被認為是 breaking change:
對于升級到新次要版本以及之前通過使用較少參數調用 super() 構造函數在其代碼庫中擴展我們的服務的任何客戶,這將導致 breaking change(特別是編譯錯誤),例如在以下示例中 :
export class CustomService extends SpartacusService {constructor(promotionService: PromotionService){super(promotionService); // <--------- wrong constructor signature/* customer's constructor logic here */}}正確做法:
// TODO(#10946): make CartItemContextSource a required dependencyconstructor(promotionService: PromotionService,// eslint-disable-next-line @typescript-eslint/unified-signaturescartItemContextSource: CartItemContextSource);/*** @deprecated since 3.1*/constructor(promotionService: PromotionService);constructor(protected promotionService: PromotionService,@Optional() protected cartItemContextSource?: CartItemContextSource) {}/* ... */method() {console.log(this.cartItemContextSource?.item$);}注意以下三點:
(1) 添加 ?使新的構造函數參數可選。否則,傳遞較少參數的客戶將收到編譯錯誤。
(2) 在類的邏輯中,允許新的構造函數參數為空或未定義。您可以通過使用可選鏈 (?.) 訪問新依賴項的任何屬性來實現此目的,例如 this.cartItemContextSource?.item$。如果不這樣做,擴展我們的類并向 super() 構造函數傳遞較少參數的客戶將在我們的邏輯中收到運行時錯誤,因為 this.cartItemContextSource 對象將是未定義的。
(3) 如果您的類可能未提供新的構造函數依賴項(例如,依賴項服務不是providedIn:‘root’,或者在DOM中有條件地提供),則在構造函數依賴項之前使用@Optional()。否則,當沒有條件提供依賴時,客戶將收到無法解析依賴的 Angular 運行時錯誤。在構造函數依賴項之前使用 @Optional() 告訴 Angular 在無法注入值時優(yōu)雅地回退到 null。
除了上述要求,我們還鼓勵您執(zhí)行以下操作:
(1) 添加內聯注釋,例如 // TODO(#ticket-number): make X a required dependency,以引用下一個主要版本的計劃工作。
(2) 在實現上方添加構造函數的兩個替代聲明。 最上面的聲明必須是最新的。
這是因為,在使用 SSR 的生產構建中,只有第一個聲明用于解決依賴關系。 將 @deprecated 自 X.Y 添加到您的 JSDoc 評論也很有幫助。 包含此內容后,客戶的 IDE 可以警告他們正在使用的舊構造函數簽名(參數較少)已被棄用,這可以促使他們盡早遷移到新簽名。
Using the Inject Decorator for Dependencie
將 @Inject 用于依賴項時,不應包含任何構造函數聲明。 相反,您應該只包含構造函數定義。
當您構建庫時(例如,當您運行 ng build --prod core 時),ng-packagr 工具僅使用第一個構造函數聲明來解析注入的依賴項,而忽略構造定義。 但是,構造函數聲明中不支持 Inject 裝飾器,因此它不能用于解析那里的依賴關系。 如果你包含一個帶有依賴的構造函數聲明,ng-packagr 工具將無法解析依賴,你會得到一個錯誤,如下所示:
ERROR: Internal error: unknown identifier []
一個錯誤的例子:
import { PLATFORM_ID } from '@angular/core'; /*...*/// Do not add any constructor declarations when using @Inject to resolve a dependencyconstructor(platformId: any, // this dependency will not be resolved, nor can it be fixed with @Inject, because the Inject decorator is not supported here!newService?: NewService) {}constructor(protected platformId: any,) {}constructor(@Inject(PLATFORM_ID) protected platformId: any,protected newService?: NewService) {}一個正確的例子:
import { PLATFORM_ID } from '@angular/core'; /*...*/constructor(@Inject(PLATFORM_ID) protected platformId: any,protected newService?: NewService) {}總結
以上是生活随笔為你收集整理的修改 Angular Component 构造函数参数被认为是 breaking change的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 180767676是哪里的dns
- 下一篇: 在阿里云 ECS 上配置 SSH