简体   繁体   中英

How to initialize Angular service, custom class from component?

I use a Angular Elements

My application has bootstrapped component as MapComponent. Also there is a core class MapCore that contains all domain logic:

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

This core class should be shared across whole Angular application. So I can make it injectable and register in root.

I need to configure this class manually from component like, therefore I use it like:

@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-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?

Could you share your expirience how to solve this issue?

I think you can do that easily using @Injectable . To do this you can update you class named MapCore like below

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=>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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