简体   繁体   English

如何从组件初始化 Angular 服务,自定义 class?

[英]How to initialize Angular service, custom class from component?

I use a Angular Elements我使用Angular 元素

My application has bootstrapped component as MapComponent.我的应用程序将引导组件作为 MapComponent。 Also there is a core class MapCore that contains all domain logic:还有一个包含所有域逻辑的核心 class MapCore

class MapCore {
   constructor(props: Props) {
       // Config here
   }
}

This core class should be shared across whole Angular application.这个核心 class 应该在整个 Angular 应用程序中共享。 So I can make it injectable and register in root.所以我可以让它可注入并在root中注册。

I need to configure this class manually from component like, therefore I use it like:我需要从组件手动配置这个 class,因此我使用它:

@Component({
  selector: 'map-root',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent {
    @Input() props: Props;
    @Input() center: Center;
    ngOnInit() {
         this.map = new MapCore(this.props);
    }
}

I need that because when I get result a custom element I can pass parameters to tag for configuration a map:我需要它,因为当我得到一个自定义元素的结果时,我可以将参数传递给标签以配置 map:

<map-root center="56,90" props="props">

My question is, how to configurate service in my case it is new MapCore custom class from component and share across application?我的问题是,在我的情况下,如何配置服务是来自组件的new MapCore自定义 class 并在应用程序之间共享?

Could you share your expirience how to solve this issue?你能分享你的经验如何解决这个问题吗?

I think you can do that easily using @Injectable .我认为您可以使用@Injectable轻松做到这一点。 To do this you can update you class named MapCore like below为此,您可以更新名为classMapCore ,如下所示

import { Injectable } from '@angular/core';

 @Injectable({
      providedIn: 'root'
    })
    class MapCore {
       constructor(props: Props) {
           // Config here
       }
    }

It will available your class across whole Angular application and you can using it like below from any component=>它将在整个 Angular 应用程序中使用您的 class,您可以像下面一样从任何组件使用它=>

export class YourComponent {
  constructor(private mapCore : MapCore ){}
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM