如何在 Web 组件中使用服务

How to use a Service into a web component

我正在尝试按照本指南制作一个 angular 网络组件: https://www.codementor.io/blog/angular-web-components-8e4n0r0zw7

它可以工作,但是当我必须将 services 注入我的组件时,如果我在构造函数中写入 (private service: DataService),我就没有任何工作了,我有一个空白屏幕并且没有控制台错误。

import {Component, Injector, Input, OnInit} from '@angular/core';
import {DataService} from '../../_service/data.service';

@Component({
  selector: 'optix-calendar',
  templateUrl: './optix-calendar.component.html',
  styleUrls: ['./optix-calendar.component.scss']
})
export class OptixCalendarComponent implements OnInit {
  @Input() apiKey = null;

  token = null;

  formData = {name: '', email: ''};
  formSubmitted = false;

  constructor(private dataService: DataService) {}

  ngOnInit(): void {
  }

  onSubmit(): void {
    this.formSubmitted = true;
  }

这是 app.module:

import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {NgModule, Injector} from '@angular/core';
import {createCustomElement} from '@angular/elements';
import {OptixCalendarComponent} from './optix-calendar/optix-calendar.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatCardModule} from '@angular/material/card';
import {HttpClient} from '@angular/common/http';


@NgModule({
  declarations: [OptixCalendarComponent],
  imports: [BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule, MatInputModule, MatCardModule

    ],
  providers: [],
  entryComponents: [OptixCalendarComponent]
})
export class AppModule {
  constructor(injector: Injector) {
    const el = createCustomElement(OptixCalendarComponent, {injector});
    customElements.define('optix-calendar', el);
  }

  ngDoBootstrap(): void {
  }
}

你能指出正确的方向以便在我的网络组件中使用服务吗?

constructor(injector: Injector) {}

 ngDoBootstrap(): void {
    const el = createCustomElement(OptixCalendarComponent, {injector});
    customElements.define('optix-calendar', el);
  }

并从您的组件中删除选择器:

@Component({
 // selector: 'optix-calendar',
  templateUrl: './optix-calendar.component.html',
  styleUrls: ['./optix-calendar.component.scss']
})

我认为您导出的是 angular 应用程序而不是 Web 组件:您调用的是 optix-calendar 而不是 app-root。