使用TypeScript进行依赖注入

时间:2019-10-26 15:32:39

标签: typescript web-component stenciljs

我的自定义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装饰的类不能具有接受参数的“构造函数”。所需的所有数据              必须使用装饰有@Prop()的类属性来传递组件

 L22:      constructor(cartService: CartService) {
 L23:          this.cartService = cartService;

我的问题是如何将服务作为依赖项注入到构造函数中? 我正在使用stenciljs构建该组件。

1 个答案:

答案 0 :(得分:0)

错误提示“用@Component装饰的类不能有带有参数的“ constructor””,因此您可以删除@Component或删除构造函数参数! 我认为您将需要@Components。让我们尝试第二个选项。

我认为这样做是不正确的,但对我来说却是可行的:

从'@ stencil / core'导入{组件};

从'../../services/cart-service'导入{CartService};删除此

导出类CheckOut {

constructor(cartService: CartService) { DELETE PARAMS

}

我将要更改的是将导入和构造器替换为此:

    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;
}

这可能很有用:

Use Methods

Using Variables