Developing a custom HTTP request class in Angular 2 and its exporting capabilities

I have created a simple HTTP requests class using Angular 2:

http-handler.ts

import {Http, Headers, RequestOptions} from 'angular2/http'
import {Injectable} from 'angular2/core';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpHandler {

    constructor(private http: Http) { }

    post(url, _body) {
        let body = JSON.stringify(_body);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(url, body, options)
            .toPromise()
            .then(res => res.json())
    }

    get(url) {
        return this.http.get(url)
            .toPromise()
            .then(res => res.json())
    }
}

I am trying to use it with a file that's bootstrapped:

login.component.ts

import {Component} from 'angular2/core';
import {Http, Headers, RequestOptions} from 'angular2/http'

import {HttpRequest} from './http-handler'

import 'rxjs/add/operator/toPromise';

@Component({
    selector: 'loginForm',
    template:`<some html>`,
})

export class LoginComponent extends HttpRequest {

    login(event) {
        var credentials = {
            "username": this.username, // username entered in a form
            "password": this.password  // password entered in a form
        }

        this.post('http://localhost/login', credentials) // method from http-handler.ts file
            .then(result => {
                if (result.correct) {
                    sessionStorage.setItem('username', this.username);
                    window.location = 'welcome.html';
                    event.preventDefault();
                    return false;
                }
                else {

                }
            })

    }
}

However, I keep getting an error from http-handler.ts: this.http is undefined. Strangely, when I copy all the methods from http-handler.ts into login.component.ts, everything works fine. Any idea what could be causing this issue?

Answer №1

What is the motivation behind making this change?

If you wish to modify the header, consider implementing something similar to the following:

    export class CustomRequestOptions extends BaseRequestOptions {

    constructor(private _authService?:AuthService) {
        super();
        var token = this._authService.token;
        if (token) {
            this.headers.set("Authorization", "Bearer " + token);       
            this.headers.set("Content-Type", "application/json");
        } else {            
            this.headers.set("Content-Type", "application/json");
        }

    }
}
@Injectable()
export class CustomHttpService {

http: Http;
constructor(http: Http,private _authService:AuthService) {
        this.http = http;
        this.http._defaultOptions = new CustomRequestOptions(this._authService);

}

}

`

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 reasoning behind triggering ValueChanges during initialization even when there are no changes detected?

I am working with a popup component that includes a mat-datepicker. When the user changes the date, I need to update this value in another control and ensure that the start and end controls are valid. However, due to a bug in the mat-date-range-input, I ...

How to retrieve the current route name or URL in AngularDart5

Exploring the OnActivate feature in Angular docs, I am attempting to utilize it to dynamically update the UI based on the current route. @Component( selector: "blah", template: """blah""", directives: const [routerDirectives]) class Blah ext ...

Excess whitespace found in string within mat-option

Every time I retrieve text from the mat-option, I notice an additional space at the end of the string. This causes my assertion to fail when trying to compare it with the expected value. This issue is new to me, and I'm unsure how to address it. Why ...

Angular 12 web version displays error message: "404 not found" for the requested URL

I recently completed my first website using Angular and uploaded it to the server successfully. When browsing through the pages, everything seems fine. However, I encountered an issue when trying to access specific URLs by copying and pasting them into the ...

The loop is returning a string element instead of the expected type from the array

I am facing an issue with looping through a TypeScript array. The following methods are being used: getNotification(evt: string, rowIndex: number) { console.log("Production order: law has changed to " + evt + " " + rowIndex); var select = document ...

Instead of using a `thisArg`, consider employing a closure when encountering problems with .pipe(map

The code I currently have is showing as deprecated. I am in need of assistance to update it, particularly the map section. There is an issue with the map part that needs attention. /** @deprecated Use a closure instead of a thisArg. Signatures accepting ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Accessing URLs directly with the Angular 2 Router

I currently have a file named main.component.ts with the following code: It can be found in: root/ import {Component, OnInit, OnChanges, IterableDiffers} from 'angular2/core'; import {TypeService} from './type/type.service'; import { ...

Interactive Typescript slider with drag functionality

Seeking assistance in developing a draggable slider using TypeScript. I have managed to retrieve the client and scroll positions, but I am struggling to change the ref scrollLeft position. There are no errors thrown; however, the ref's scrollLeft prop ...

What is the best approach: Developing a class or a service to handle multiple interfaces?

My current project involves creating multiple interfaces, and I would like to keep them separate for clarity. Would it be wise to do this in a service or a class? Additionally, is it possible to utilize dependency injection for classes? Thank you for your ...

Angular API for search filtering input

I am currently retrieving data from an API in my service. I now need to implement a search filter by name. Here is the code for the Service: export class ListService { listUrl = 'https://swapi.co/api/planets'; constructor(private ht ...

Steps to automatically make jest mocked functions throw an error:

When using jest-mock-extended to create a mock like this: export interface SomeClient { someFunction(): number; someOtherFunction(): number; } const mockClient = mock<SomeClient>(); mockClient.someFunction.mockImplementation(() => 1); The d ...

What causes the lack of minlength validation when the form is in its initial state?

Check out the code snippet below: <input [(ngModel)]="someProperty" minlength="5" /> I recently ran my app and used the browser debugger tool to inspect the state of this input field. Surprisingly, I noticed that it was marked as ...

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

Unusual title attributed to saving the date in Firebase

Could anyone explain why my JSON appears like this https://i.stack.imgur.com/xzG6q.png Why does it have a strange name that starts with -M-yv... instead? I am saving my data using the http.post method, passing the URL to my database and an object to save ...

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...

Tips for retrieving an object using a key in javascript or typescript when the key is unknown

Could someone help me figure out how to access the 'value' key in this object? { '-L7uAVxXmuLeBN1K-B0_': { timestamp: '18:35:18', value: 19.81 } } I'm not familiar with the first key, '-L7uAVxXmuLeBN1K-B0_', b ...

Creating an Angular template using the Teams Toolkit within Visual Studio Code

I'm looking to create a basic step-by-step form on Microsoft Teams using my existing Angular application. However, I've noticed that there are only React templates available in Visual Studio Code for building tabs in Teams. Do I have to use these ...

Obtain an array containing various directives in a specific sequence

I am looking to extract directives from the view or content in the exact sequence they were specified in the template. First Attempt [view plunker] @Directive({selector: 'dir-1'}) class Dir1 {} @Directive({selector: 'dir-2'}) class Di ...

Exploring the incorporation of asynchronous functionality within Angular Material's Matstepper component

Currently, I am implementing the Stepper component from Angular Material2 in conjunction with Angular4. Component1 <mat-horizontal-stepper #stepper> <mat-step></mat-step> <mat-step></mat-step> </mat-horizontal-stepper> ...