Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project?

Here is an example of what I am aiming for.

ServiceClass

@Injectable()
export class MyService {
    constructor(private parent: MyComponent){ // <- Somehow get a reference from the component I inject this into?
        parent.doStuff();
    }
}

ComponentClass

@Component({
  selector: 'project-a-component',
  template: `
    <div>stuff</div>
  `,
  styleUrls: ['./a.component.scss']
})
export class AComponent implements MyComponent {
    constructor(private myService: MyService){ }

    doStuff(): void {
        console.log('yey!');
    }
}

Edit: My goal is to listen to the OnDestroy event for a component in order to run .pipe(takeUntil(parent.isDestroyed)) to unsubscribe a subscription without having to add it manually every time I use my services in my project or pass a reference to my parent component in each method call. Having the reference available in the constructor (or just one place) would be ideal. Trying to explain the issue as clearly and simply as possible.

Answer №1

Check out this interesting article on how to automatically unsubscribe in Angular: . By hooking into the OnDestroy lifecycle method of components, you can customize your own behavior:

export function MyDecorator( constructor ) {
  const original = constructor.prototype.ngOnDestroy;
  constructor.prototype.ngOnDestroy = function () {
    if (this.myService) {
      // Perform custom actions here
    }
  };
}

You can follow the example provided in the article to automatically unsubscribe all subscriptions, not just for a single service. Import the decorator into your component and apply it like this:

@MyDecorator
export class MyComponent {
// ...

Answer №2

I found a helpful approach to managing this issue by creating a method within my service that takes the component's interface and assigns it to a variable within the service itself. By calling this method in the ngOnInit() lifecycle hook wherever it is needed, I was able to significantly reduce the amount of code within my components. It seems like a practical and efficient way to handle this task.

@Injectable()
export class DataService {
    private currentComponent: MyComponent;

    constructor(){}

    setCurrentComponent(component: MyComponent): void {
        this.currentComponent = component;
    }
}

@Component({
  selector: 'project-b-component',
  template: `
    <div>content goes here</div>
  `,
  styleUrls: ['./b.component.scss']
})
export class BComponent implements MyComponent {
    constructor(private dataService: DataService){
        dataService.setCurrentComponent(this);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Observing with starting value

When using an observable, I am trying to filter and display a list. The input event is only fired when the user starts typing, so initially the list is not displayed. How can I set a default value for the observable this.filterLocation$ until the input eve ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...

Tips on ensuring dispatch is finished before accessing store data. Ngrx dilemma

Is there a way to ensure that a dispatch is completed before selecting from a store? I haven't had any luck finding a solution online. How can I make sure the dispatch finishes before selecting from the store? I would appreciate any help with my code ...

Is there a way to set the size of my unique carousel design?

Having some trouble with my modal image carousel; the dimensions keep shifting for different image sizes. Image 1 Image 2 ...

Utilizing session management in Angular while handling CORS origin requests

Everything was going smoothly with my session until I decided to enable CORS. Server: app.use(require('express-session')({ secret: 'some key', resave: true, saveUninitialized: true, proxy: true, cookie: { s ...

What are some strategies for validating form fields in the Back-End and displaying them in Angular7?

My plan is to develop the backend of my app using Spring Boot and the frontend using Angular. I want to ensure the security of the form field information by validating it on the backend side. To get started, I created a model called Visitor.java with the f ...

Searching for variables within files using Node.js and constructing an object from the results

Trying to figure out how to streamline this process. Here's the directory structure I'm working with: src/ modules/ clients/ i18n/ en-US.ts tasks/ i18n/ en-US.ts So, ea ...

Custom styles for PrimeNG data tables

Struggling to style the header of a datatable in my Angular project using PrimeNG components. Despite trying various solutions, I am unable to override the existing styles. Even attempting to implement the solution from this PrimeNG CSS styling question o ...

Incorporating npm packages into an Angular2 (v2.0.0-rc.1) application

Struggling with integrating npm libraries into my Angular2 app has been a challenge, especially when trying to include https://github.com/manfredsteyer/angular2-oauth2. Every time I try to import the library, I encounter a 404 error. Even after adding the ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

The blur event in Angular Material's mat-date-range-input does not trigger if the End Date is not selected

I am currently utilizing Angular 15 along with Angular Material 14. The code for the DatePicker control is shown below. <mat-form-field class="datepicker-widget" appearance="fill"> <mat-date-range-input [formGroup]="d ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

I'm experiencing issues with event.preventDefault() not functioning properly when used within a contenteditable div

I'm currently working with some basic Angular 7.x code that involves a contenteditable div. I'm attempting to prevent the default action when a user hits the [ENTER] key, but no matter what I do, it still moves the cursor to the next line. What a ...

Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using setValue or patchValue However, I am currently encountering a situation where I need to avoid setting the value on each field individually. Take a look at my f ...

Navigating to the end of a list using Angular's scroll feature

I'm trying to figure out how to automatically scroll to the bottom of a list in TypeScript, can someone help me with this? Here's a similar example I found that uses jQuery (I specifically need it in TypeScript): Scroll to bottom of list wit ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Using ngModel in multiple mat-select elements in Angular 2/4

I have a mat-select dropdown list that allows multiple selections and I am using NgModel to keep track of the user's selected values. The issue arises when I navigate away from the page and return, the user's selected values are not preserved in ...

How to transfer the label text value from html to .ts file in Ionic 3?

Hey everyone! I just started using Ionic and I'm wondering how to pass the value of a label text from HTML to the .ts file. Here's a snippet of my code: <div class="box" (click)="openChatBot()"></div> <ion-label>LEADER ...

What is the process of organizing information with http in Angular 2?

Currently, I am working through a heroes tutorial and have made progress with the code so far. You can view the code <a href="https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?preview" rel="nofollow noreferrer">here</a>. My next goal is to implement ...