Search code examples
angularangular-servicesangular-components

I currently have an Angular service that contains the functionality I need. How can I have the service interact with a component?


I would like to know how I can successfully have my service pass its data to the required component that is located in a different directory.

Component

import {Component, Inject, OnInit} from '@angular/core';

import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';

@Component({
  selector: 'app-add-view-modal',
  templateUrl: './add-view.component.html',
  styleUrls: ['./add-view.component.css']
})
export class AddViewComponent implements OnInit {

constructor(public dialogRef: MatDialogRef<AddViewComponent>,
  @Inject(MAT_DIALOG_DATA) data) {}

  ngOnInit() {
  }
}

Solution

  • You can just use Angular's automatic dependency injection:

    import {ViewManagerService} from 'path/to/view-manager.service.ts';
    import {Component, Inject, OnInit} from '@angular/core';
    import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
    
    
    @Component({ selector: 'app-add-view-modal', templateUrl: './add-view.component.html', styleUrls: ['./add-view.component.css'] })
    
    export class AddViewComponent implements OnInit {
    
    constructor(
       private viewManagerService: ViewManagerService,
       public dialogRef: MatDialogRef<AddViewComponent>,
       @Inject(MAT_DIALOG_DATA) data
    ) {
    }
    
    ngOnInit() {
       this.viewManagerService.doSomething();
    }
    }