Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用TypeScript进行依赖注入_Typescript_Web Component_Stenciljs - Fatal编程技术网

使用TypeScript进行依赖注入

使用TypeScript进行依赖注入,typescript,web-component,stenciljs,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: CartServic

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

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

错误是“用@component装饰的类不能有带参数的“构造函数”,因此您可以删除@component或删除构造函数参数! 我认为您将需要@组件。让我们试试第二种选择

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

从'@stencil/core'导入{Component}

从“../../services/cart-service”导入{CartService};删除这个

导出类签出{

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;
}
这可能是有用的:


由于与Stencil不支持继承相同的原因,您无法控制Stencil组件的构造函数:避免类层次结构的动态分析;使其更易于在library land中实现和维护。您需要使用错误消息指定的属性。您可以使用工厂和直接h('CheckOut',{cartService:cartService})转发依赖项,或使用方法并在以后转发依赖项。您还可以使用某些约定并在组件加载时从全局依赖项服务请求依赖项。
initialize() {
   ...
  let CartService = document.body.appendChild(document.createElement('cart- 
   service'));
   this.cartService = CartService.CartService;
}