0

I have a created a custom web component using angular elements which needs to call a method in main application service.ts.

custom element

@Component({
      templateUrl: './sample.component.html',
      styleUrls: ['./sample.component.css']
   })
   export class SampleComponent{
   constructor(){
   //here i want to call the main application's service method.
   }
}

MainApplication.service.ts

@Injectable({
 providedIn: 'root'
})
export class StoreService {
   getData(): Observable<Model> {
   return this.dataSource.asObservable();
 }
}

My issue is that i want to call getData() from the custom element. Provided that i have already induced the custom element in MainApplication.component.ts. Emitting some data from custom element to the parent component is easy using eventEmitters and @Output, but when it comes to calling a service method which can provide some data in return, is there any way to do it?

  • Only way I can think of is that you have to pass the service as `@Input()` to the custom element, apart from a very hacky way by binding the service to the window object – Poul Kruijt Apr 24 '20 at 11:16
  • try using Subject or BehaviorSubject – Piyush Jain Apr 24 '20 at 11:18
  • You can expose an event and a bindable property. In the parent component, you add an event handler that updates the property value bound to the child component after getting data from service. – Eldar Apr 24 '20 at 11:20

1 Answers1

0

I know this is a bit late, but yes, you can:

@Component({
      templateUrl: './sample.component.html',
      styleUrls: ['./sample.component.css']
   })
   export class SampleComponent{
   constructor(private storeService: StoreService){
       this.storeService.getData()
   }
}
Harry Allen
  • 385
  • 4
  • 13