Hand over the component method as an argument to a class

One of my components, called First, is responsible for creating a new instance of a Worker class.

During the creation process of this class, I intend to pass the Read method as a callback method. Once this class completes its task, it will then invoke this method.

I have previously implemented this functionality in vanilla JavaScript. My question is, can I achieve the same in Angular 6?

@Component({
   selector: 'app-campaign-settings',
   templateUrl: './campaign-settings.component.html',
   styleUrls: ['./campaign-settings.component.css']
})
export class First implements OnInit {

worker: Worker = null;

Work() {
    worker=new Worker(this.Read);
    worker.Run();
}

Read() {
    // Perform necessary operations

}

}

export class Worker implements OnInit {

callback: any;

constructor(i_callback: any) {
    // Initialize
}

Run() {
    callback();
}

}

Answer №1

In the world of Angular, it is strongly advised against passing callbacks or references to other classes.

Instead, parents can listen for events emitted by children and then execute the desired code without the need for callbacks.

This approach allows the child to operate independently without any knowledge of the parent's existence or methods.

Check out an example of an Event Emitter and Subscriber here.

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

What is the reason for the allowance of numeric keys in the interface extension of Record<string, ...>

I am currently working on a method to standardize typing for POST bodies and their corresponding responses with API routes in my Next.js application. To achieve this, I have created an interface that enforces the inclusion of a body type and a return type ...

Angular 11 - Error: The 'fetch' method could not be executed on the 'Window' object due to an illegal invocation

I have encountered an issue with a dependency in my current project. This particular dependency relies on isomorphic-unfetch for its functionality. Strangely, I am able to run isomorphic-unfetch without any problems within Angular 11. However, when I inclu ...

Troubleshooting: Issues with APIGateway's Default Integration

I'm currently utilizing the AWS CDK to construct my API Gateway REST API My objective is to have my RestApi configured to automatically return an HTTP 404 error, so I set it up as follows: this.gateway = new apigw.RestApi(this, "Gateway", { ...

Encountering Type Error in Angular 2

Here is the Angular 2 code snippet I am working with: <ion-grid *ngFor="let item of menuData; let i = index;" ng-init="getAllItemToGrid()"> <img src="{{'assets/Products/'+menuData[i].image}}" ng-click="onLogin()" width="100%"> ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

Angular allows for the easy population of an array into an input box

I've been given a task to create 10 different input forms and populate them with an array of 10 users using Angular's looping functionality. By the end of this task, I expect to have 10 input forms filled with various user data from the array. ...

Tips for expanding interfaces/classes during variable declaration

Is it possible to extend an interface or class during variable declaration? For instance: export declare abstract class DynamicFormControlModel implements DynamicPathable { asyncValidators: DynamicValidatorsConfig | null; _disabled: boolean; ...

Utilizing emotion with MUI v5 for dynamic theming

After upgrading MUI from v4 to v5, I'm facing some difficulties grasping the concept of theming with the various solutions available. I find it challenging to determine when to use MUI theming/styling components and when to opt for emotion ones. Whil ...

Utilizing models to establish the data type of an Observable within Angular

I have a simple query regarding a service. I have a method called getAllArticlesFromDb in my service that retrieves data from an API using an HTTP GET call. Here is the code for the method: article.service.ts getAllArticlesFromDb() : Observable<any> ...

Having trouble launching myapp on the Android Studio emulator for Ionic 3

My current project involves using Ionic with Cordova to develop an app without any visible errors in the CLI. I am also utilizing Android Studio to emulate the app. In addition, I am relying on the Chrome inspect feature to monitor my app's behavior ...

Angular 2: Troubleshooting Issues with Observable Data Display

Looking to implement a RESTful call with Angular 2 that constantly updates whenever there are changes in the API. In my service, I've included an Observable to fetch data from the API: getData(): Observable<any[]> { return this.http.get(url) ...

Unable to run 'ng serve -o', however 'ng serve' functions correctly

Encountering an issue with Angular when attempting to configure the Micro frontend Framework (module federation) for both the remote and host applications. They are not located in the same workspace. When running the remote app with "ng serve -o", an error ...

What could be causing my Angular Ngrx app's state not to render properly on the application?

Is there a way to automatically render the state when the app loads without having to click a button? I am currently facing an issue where the state is empty until I manually trigger the click function by pressing a button. I have tried using this.store.se ...

Creating a generic class in Typescript that can only accept two specific types is a powerful

When designing a generic class, I am faced with the requirement that a property type must be either a string or number to serve as an index. If attempting something like the code snippet below, the following error will be triggered: TS2536: Type 'T ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...

Suggestions for maintaining order in a multiselect PrimeNG while using it to conceal table columns

Currently, I am implementing a multiselect PrimeNG feature to show or hide columns in my ptable. While it works well for hiding columns, the issue arises when attempting to show them again. Instead of returning to their original order, the columns are be ...

Using Multiple Router Outlets in Angular 4

<div *ngIf="!loggedIn" class="login"> <router-outlet></router-outlet> </div> <div *ngIf="loggedIn" class="main"> <router-outlet></router-outlet> </div> Containing within this code snippet are a login co ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

Having trouble accessing HikVision Web SDK functions in Angular 17

First and foremost, this concerns the HikVision cameras specifically. Because the SDK is compiled to plain JavaScript (with jQuery included), I had to import the JS files in angular.json and use declare in the component TS file (in this instance, camera.c ...

Sending detailed exception information from asp.net core to the client (such as Angular)

Trying to retrieve exception text from the backend (ASP.NET Core) in an Angular application has been a challenge. Examples have shown the controller action's return type as either JsonResult or ActionResult. In such cases, we can utilize the followi ...