What is the process of extending a class in TypeScript?

I have a few services that contain the same code:

 constructor (private http: Http) {
    //use XHR object
    let _build = (<any> http)._backend._browserXHR.build;
    (<any> http)._backend._browserXHR.build = () => {
        let _xhr =  _build();
        _xhr.withCredentials = true;
        return _xhr;
    };
}

I would like to refactor this code into a separate file called http_base_clas.ts and reuse it as much as possible. Here is http_base_clas.ts:

import {Http} from '@angular/http';

export class HttpBaseClass {
    constructor ( http: Http) {
        //use XHR object
        let _build = (<any> http)._backend._browserXHR.build;
        (<any> http)._backend._browserXHR.build = () => {
            let _xhr =  _build();
            _xhr.withCredentials = true;
            return _xhr;
        };
    }
}

How can we extend http_base_class into auth_service.ts?

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable ()

export class AuthenticationService {
result: {
    ok: boolean;
};
private verifyUrl = 'http:example.com;  

constructor (private http: Http) {

}
private authRequest (url) {
    let body = JSON.stringify({});
    let headers = new Headers({ 'Content-Type': 'application/json'});
    let options = new RequestOptions({
        headers: headers
    });
    return this.http.post(url, body, options)
        .map((res: Response) => res.json())
        .map(res => {
            this.result = res;
            return this.result.ok;
        });
    }
}

Answer №1

class SecureService extends HttpRequestHandler {
  constructor(httpRequest:HttpRequest) {
    super(httpRequest);
  }

  private makeSecureRequest (url) {
    ...
  }
}

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

Retrieving data and parameter data simultaneously from the ActivatedRoute

I am currently utilizing Angular and have a webpage where I need to send data to another page. Transmit an array of selected values Generate multiple records (associating with a model) this.activatedRoute.data.subscribe(({ model] }) => { setTim ...

Mastering the proper usage of the import statement - a guide to seamless integration

I'm excited to experiment with the npm package called camera-capture, which allows me to capture videos from my webcam. As someone who is new to both npm and typescript, I'm a bit unsure about how to properly test it. Here's what I've ...

Error message in Visual Studio 2017: Identical name 'URLs' declared twice in

In our Visual Studio 2017 project, we have multiple TypeScript files that define a URLs class. Each file contains different implementations of the class to change site URLs based on the specific use case: customer/urls.ts namespace Portal { export cl ...

Solving the issue of refreshing HTML Canvas drawings in Vue3 using the Composition API

In my typescript code base, I have successfully created a Sudoku board by directly manipulating the DOM and utilizing an HTML Canvas element with its API. Now, I am looking to elevate my project to a full website and integrate what I have into a Vue3 proj ...

TypeScript throws an error if trying to access an Object variable using a String

While the code below is functioning as intended, I am encountering an error in the VS Code Typescript compiler stating that "Type 'String' cannot be used as an index type". Oddly enough, using a string literal instead of a variable like ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

The data stored in the variable cannot be accessed when calling it in a different method

Within my component, there are several methods including constructor(){...} and ngOnInit(){...}. I have declared a variable named values:any=[] in the class, and it is initialized with JSON data within a method called getData(). getData(){ this.service. ...

Creating a TypeScript type based on the static values of a class

In my Market class, there is only one parameter: name. class Market { name: string constructor(name: string) { this.name = name } } Next, I have a Markets class that contains a static collection of multiple markets. class Markets { static M1 ...

When there is data present in tsconfig.json, Visual Studio Code does not display errors inline for TypeScript

After creating an empty .tsconfig file (consisting solely of "{ }"), Visual Studio Code immediately displays errors both inline and in the "problems" section. Interestingly, when I populate the tsconfig.json file with data, these errors disappear. Is there ...

How can I utilize formGroupName and pass it to a different component?

Here is the template I am working with: <mat-form-field class="dense no-bottom" appearance="fill" style="min-width: 8em; flex: 1;"><mat-label>{{ label | translate}}</mat-label><mat-select formControlName=& ...

Issue with IE11 compatibility in Angular2 (AngularQuickStart version 2.4.0) due to syntax error

Encountering an error in the browser console when attempting to run my Angular2 app on IE11. The error "Недопустимый знак" translates to unacceptable symbol. https://i.stack.imgur.com/0mHBC.png Here is a snippet of my index.html: <!DO ...

Harmonize the connectivity between an Angular - .NET application and the Google Calendar API

I am currently working on integrating the Google Calendar API into my angular .NET application using OAuth2. The goal is to allow each user to see their own calendar as soon as they log in. One idea I have is to save the generated code into our database f ...

Deactivate the button if the mat-radio element is not selected

Here is my setup with a mat-radio-group and a button: <form action=""> <mat-radio-group aria-label="Select an option"> <mat-radio-button value="1">Option 1</mat-radio-button> <mat-radio-b ...

The type 'FormikValues' is deficient in the subsequent properties compared to the type 'Exact<{'

I am currently working on a form with the following structure: import { Field, Form, Formik, FormikProps, FormikValues } from 'formik' import { NextPage } from 'next' import React from 'react' import { useCreateUserMutation } ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...

Exporting modules in TypeScript using "module.exports"

While working on my Yeoman generator, I initially wrote it in JavaScript like this: "use strict"; var Generator = require("yeoman-generator"); var chalk = rquire("chalk"); module.exports = class extends Generator { initializing() { this.log( c ...

Unleash the power of zod by seamlessly accessing both parameters and queries

In the zod-middleware documentation, an example is provided: export async function endpointCode(req: TypedRequestBody<typeof bodySchema>, res: Response) { const typedBody = req.body; return res.json(typedBody); } This example demonstrates access ...

Angular 5: Display a blank URL with the source until the variables are resolved

In my template, if I have: <img src="/somepath/{{user?.UserGuid}}.png" /> When user is not yet resolved, the ?. prevents evaluating UserGuid, resulting in: <img src="/somepath/.png" /> Is there a way to prevent this without using *ngIf or c ...

Double firing issue with ngModelChange when paired with ng DateTimePicker in Angular 7

When utilizing the ng datetimepicker library in Angular to display a date time picker, I'm experiencing an issue where the method triggered by (ngModelChange) fires twice simultaneously, causing the changed date to be logged twice in the console. Can ...