Ensuring Function Parameter Usage in Typescript and Angular 5

Currently, I am developing a component using Angular 5 and Ionic 4.

My objective is to include a Refresher event to hide the refresh spinner whenever the user triggers the final function to conceal the spinner.

Provided below is an excerpt of my code:

export class UserInfoService {

    constructor(private employeeService: EmployeeService) {
        this.handleSuccess = this.handleSuccess.bind(this);
        this.processData = this.processData.bind(this);
        this.handleFinally = this.handleFinally.bind(this);
    }

    getEmployeeInfo(event?: Refresher) {

        // console.log(event);

        return this.employeeService
            .getEmployeeInfo()
            .map(this.handleSuccess)
            .finally(this.handleFinally);
            // .finally(() => {
            //     if (event != null) {
            //         console.log(' event ', event);
            //         event.complete();
            //     }
            // });
    }

    handleFinally() {
        console.log(' handle finally ', event);

        if (event != null) {
            console.log(' event ', event);
            event.complete();
        }
    }

The commented portion of the code works properly, although it would be more efficient not to utilize an anonymous function. By binding it to the constructor, it can detect other events seamlessly.

Answer №1

Ensure the event value is included. Consider setting it as a parameter of handleFinally. Although an anonymous function is still required, it becomes more concise without sacrificing readability:

export class UserInfoService {
  constructor(private readonly employeeService: EmployeeService) {
      this.handleSuccess = this.handleSuccess.bind(this);
      this.processData = this.processData.bind(this);
  }

  getEmployeeInfo(event?: Refresher) {
      // console.log(event);

      return this.employeeService
          .getEmployeeInfo()
          .map(this.handleSuccess)
          .finally(() => this.handleFinally(event));

  }

  handleFinally(event?: Refresher) {
      console.log(' handle finally ', event);

      if (event) {
          console.log(' event ', event);
          event.complete();
      }
  }
}

Answer №2

Using array functions with function variables is still possible, as demonstrated in the example below:

export class UserInfoService {

  constructor(private employeeService: EmployeeService) {
      this.handleSuccess = this.handleSuccess.bind(this);
      this.processData = this.processData.bind(this);
  }

  getEmployeeInfo(event?: Refresher) {

      // console.log(event);

      return this.employeeService
          .getEmployeeInfo()
          .map(this.handleSuccess)
          .finally(this.handleFinally);

  }

  handleFinally = (event?: Refresher) => {
      console.log(' handle finally ', event);

      if (event != null) {
          console.log(' event ', event);
          event.complete();
      }
  }
}

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

"Manipulating values in an array with a union type: a guide to setting and

I am currently working on creating an array that can have two different value types: type Loading = { loading: true } type Loaded = { loading: false, date: string, value: number, } type Items = Loading | Loaded const items: Items[] = ...

Unable to bring in Angular2 bootstrap function

I am currently setting up a basic Angular 2 (beta 2) app using TypeScript. I have the code for app.ts file taken from Angular's most recent setup guide import {Component, View, bootstrap} from 'angular2/angular2'; @Component({ selector: ...

Troubleshooting Error in Converting a JSX File with Tailwind CSS and Typescript

I found a code example on the Tailwind website. However, when I changed the file extension to .tsx, I encountered an error related to the className attribute. Do I need to specify a type for the className variable? What steps should I take to resolve thi ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

Unusual behavior observed during npm update operation

Just starting out with Angular and NPM, I have encountered a puzzling situation. I have two Angular-CLI projects. When I run npm update --save in one project, the dependencies (including @angular dependencies) are updated from version ^5.2.0 to ^5.2.3 in ...

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

Differences Between APP_INITIALIZER and platformBrowserDynamic with provide

I've discovered two different approaches for delaying an Angular bootstrap until a Promise or Observable is resolved. One method involves using APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: (configService: ConfigurationService) => ( ...

What is the process for bringing in AngularJS 2? // Bring in { routerTransition } from './router.module;

Currently, I'm experimenting with implementing page transitions using Angular 2. The resources I've gone through indicate that I need to import: // import { routerTransition } from './router.module; However, despite following these instruc ...

The karma test encounters difficulties in establishing a connection with the 'chrome' instance that has been launched

Currently, I am facing an issue with my Karma test running on a nodejs jenkins pod. npm is timing out when trying to connect to the Chrome instance on the selenium hub. Everything was working fine until yesterday without any changes made to the configura ...

The selected data was inserted as a foreign key, leading to an Integrity constraint violation with SQLSTATE[23000]: 1048

Hello and thank you for joining us! I am currently working on a task that involves selecting the acc_id from the account_info table and inserting it as a Foreign Key into the patient_info table. Unfortunately, I have encountered an error: While testing ...

When using Google Chrome, you may encounter an error message stating that the 'Access-Control-Allow-Origin' header in the response cannot be set to a wildcard '*' even when a specific URL is specified

In my web application, I've utilized Angular 9 for the frontend and nodejs for the backend. The CORS middleware setup in my Express JS server is as follows: const corsOptions = { origin: [ "http://localhost:4200", ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Angular does not update the progress bar

Imagine having a component html with your own customized round progress bar <round-progress #progress [current]="current" </round-progress> The "Current" value represents the percentage. In my TypeScript component, I have written: ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

Struggling to deploy a Typescript React / NestJS application on Heroku due to the error message "error TS2307: Cannot find module"?

Switching from a Typescript React/Express app to using Nest.JS has caused complications when deploying to Heroku. The app runs smoothly locally, but encounters build failures on Heroku. Despite efforts to troubleshoot, it remains unclear whether the issues ...

Unable to access the API within Angular using a web browser

My Angular application is hosted within an ASP.NET Core application on IIS. The API controller of the ASP.NET Core application can be accessed using the HTTP client in Angular as well as in a C# console application. However, I am facing an issue where I c ...

What is the process for launching a TypeScript VS Code extension from a locally cloned Git repository?

Recently, I made a helpful change by modifying the JavaScript of a VSCode extension that was installed in .vscode/extensions. Following this, I decided to fork and clone the git repo with the intention of creating a pull request. To my surprise, I discove ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

Issues with running NPM script for compiling TypeScript code

[UPDATE] Initially, I resolved this issue by uninstalling tsc using npm uninstall tsc (as recommended in the response marked as the answer). However, the problem resurfaced after some time, and eventually, I found success by utilizing Windows Server for L ...