[英]Dependency Injection With TypeScript
我的自定義 web 組件中有以下構造函數:
import { Component} from '@stencil/core';
import { CartService } from '../../services/cart-service';
@Component({
tag: 'check-out',
styleUrl: 'check-out.css'
})
export class CheckOut {
private cartService: CartService;
constructor(cartService: CartService) {
this.cartService = cartService;
}
componentDidLoad() {
this.initialize();
}
initialize() {
...
}
render() {
return [...];
}
}
現在的問題是,每當我嘗試構建時,都會出現以下錯誤:
src/components/check-out/check-out.tsx:22:17 用@Component 修飾的類不能有一個采用 arguments 的“構造函數”。 組件所需的所有數據都必須使用帶有 @Prop() 修飾的 class 屬性傳遞
L22: constructor(cartService: CartService) { L23: this.cartService = cartService;
我的問題是如何將我的服務作為依賴項注入到構造函數中? 我正在使用 stenciljs 來構建組件。
錯誤說“用@Component 裝飾的類不能有一個帶參數的“構造函數””,因此您可以刪除@Component 或刪除構造函數參數。 我認為您將需要@Components。 讓我們試試第二個選項。
我認為這樣做是不正確的,但它對我有用:
從'@stencil/core'導入{組件};
從'../../services/cart-service'導入{ CartService }; 刪除這個
出口 class 結帳 {
constructor(cartService: CartService) { DELETE PARAMS
}
我將改變的是將 IMPORT 和 CONSTRUCTOR PARANS 替換為:
let CartService = document.body.appendChild(document.createElement('cart-service'));
this.cartService = CartService.CartService;
現在初始化:
initialize() {
...
let CartService = document.body.appendChild(document.createElement('cart-
service'));
this.cartService = CartService.CartService;
}
這可能很有用:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.