Creating a customized HTTP class for Bootstrap in Angular 2 RC 5

During my experience with Angular 2 RC 4, I encountered a situation where I needed to create a class called HttpLoading that extended the original Http class of Angular2.

I managed to integrate this successfully into my project using the following bootstrap code:

bootstrap(AppComponent, [
    HTTP_PROVIDERS,
    provide(RequestOptions, { useClass: DefaultRequestOptions }),
    provide(Http, {
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new HttpLoading(backend, defaultOptions),
        deps: [XHRBackend, RequestOptions]
    })
]).catch(err => console.error(err));

This is how my DefaultRequestOptions class looks like:

import { Injectable } from '@angular/core';
import { Headers, BaseRequestOptions } from '@angular/http';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {
    headers: Headers = new Headers({
        'Content-Type': 'application/json'
    });
}

Here is the structure of my HttpLoading Class:

import { Http, RequestOptionsArgs, ConnectionBackend, RequestOptions, Response } from '@angular/http'
import { Injectable } from '@angular/core'
import {GlobalService} from './globalService';
import { Observable } from 'rxjs/Observable';

export class HttpLoading extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _globalService: GlobalService) {
        super(backend, defaultOptions);
    }

    get(url: string, options?: RequestOptionsArgs): Observable<any> {
        this._globalService.isLoading = true;
        return super.get(url, options)
            .map(res => {
                this._globalService.isLoading = false;
                return res.json();
            })
            .catch(this.handleError);
    }
}

However, with RC 5, I am facing challenges in migrating this code snippet to the NgModule providers list.

After referencing the migration guide, I updated my NgModule as follows:

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule }   from '@angular/forms';
import { HttpModule }     from '@angular/http';
import { Http, HTTP_PROVIDERS, RequestOptions, XHRBackend } from '@angular/http';

import { DefaultRequestOptions } from './DefaultRequestOptions';
import { HttpLoading } from './http-loading';

import { routing }        from './app.routing';
import { AppComponent } from './components/app.component';


@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule,
        routing
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        HTTP_PROVIDERS,
        { provide: RequestOptions, useClass: DefaultRequestOptions },
        {
            provide: Http,
            useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, globalService: GlobalService) => new HttpLoading(backend, defaultOptions, globalService),
            deps: [XHRBackend, RequestOptions, GlobalService]
        }
    ],
    bootstrap: [AppComponent],
})
export class AppModule { }

Unfortunately, it seems like the custom Http service is not being properly added because when I use http in my component, it still defaults to the standard http implementation instead of my customized one.

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    templateUrl: '../../templates/home/home.html'
})
export class HomeComponent implements OnInit {

    constructor(private http: Http) {}

    ngOnInit() {
        this.http.get('/home')
            .subscribe((data) => {

            });
    }
}

If anyone can provide guidance on resolving this issue, it would be greatly appreciated. Thank you!

Answer №1

After upgrading to >=RC5, the approach changes to bootstrapping an @NgModule class instead of the root component. For more information, you can refer to this guide for transitioning from RC4 to RC5.

import { NgModule }       from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent }   from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [HttpModule],  // no need for HTTP_DIRECTIVES
  providers: [
    {provide: RequestOptions, useClass: DefaultRequestOptions },
    {provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new HttpLoading(backend, defaultOptions), deps: [XHRBackend, RequestOptions]}
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

Answer №2

Big thanks to all of you for your assistance! The problem has been solved by eliminating the following code snippet:

{ provide: RequestOptions, useClass: DefaultRequestOptions },

It appears that this code is no longer necessary with RC 5.

Answer №3

Encountered a similar problem, but found the solution by setting the body of the request to an empty string.

When using the http.get method with a "RequestOptions" parameter, remember to set the body property to ''. Here's an example:

.http.get(BaseService.apiUrl + api/someMethod, { body: '' }) ...

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

Utilizing the params property of ActivatedRouteSnapshot to dynamically populate data within a component

Picture a scenario where we have a single component that needs to be filled with data based on different URL parameters. Consider the following URL patterns: 1. http://localhost:4200/venues/5760665662783488 2. http://localhost:4200/users/2gjmXELwGYN6khZ ...

Failure to log in to Facebook via Angular and Google Firebase due to URL being blocked

I am currently in the process of developing a web application that aims to gauge political popularity. To ensure accurate polling data, users will need to authenticate their social media accounts including Facebook, Twitter, and Google. For the front-end ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

When combining Angular with Workbox, you may encounter a ChunkLoadError stating that the loading of a specific chunk was refused to execute due to mismatch

When I added Workbox to Angular for the first production deployment, everything worked smoothly. However, after updating a module, rebuilding Angular, and injecting Workbox again, I encountered an issue. Upon visiting the site, I noticed that the service w ...

Creating a local HTML file using node.js: A step-by-step guide

Recently, I've delved into developing games using Typescript. However, I've encountered a bit of an issue when attempting to build my game - it requires running on a server. This limitation prevents me from creating an offline game with Node.js a ...

Exploring type delegation in TypeScript

Here is a scenario where I am using the builder pattern in my code: export class ValidationBuilderBase implements IValidationBuilder { public isRequired(): IValidationBuilder { const validationResult = Validators.required(this.baseControl); ...

Testing units in Angular using different sets of test data

When it comes to unit testing a C# method with different sets of data, the Theory and InlineData attributes can be used to pass multiple inputs for testing purposes. [Theory] [InlineData("88X", "1234", "1234", "1234")] [InlineData("888", "123X", "1234", " ...

Error encountered when extending Typography variant in TypeScript with Material UI v5: "No overload matches this call"

Currently, I am in the process of setting up a base for an application using Material UI v5 and TypeScript. My goal is to enhance the Material UI theme by adding some custom properties alongside the default ones already available. The configuration in my ...

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

Error encountered in spyOn TS when passing array iteration instead of a string

Instead of repeating test cases with minor adjustments, I have implemented an Array and iterated through it. However, I am encountering a TS error in test when passed from the Array instead of as a string testLink Error: No overload matches this call. ...

Combining Angular, Node.js, and Spring Boot Java REST API to enable Angular Universal functionality

I am seeking guidance on integrating Angular with NodeJS and Spring Boot for my application. Currently, I have built a system that utilizes Angular for the frontend and Java/Spring Boot for the backend REST API. However, I have come across challenges with ...

Angular 7 is taking an unusually long time to load the after login component

Upon logging into my Angular 7 application, the after-login component experiences slow loading for the first time. However, if a user logs out and then logs back in without closing the browser, the speed improves. The routing structure is as follows: In ...

Injecting services with an abstract class is a common practice in Angular library modules

In my development workflow, I have established an Angular Component Library that I deploy using NPM (via Nexus) to various similar projects. This library includes a PageComponent, which contains a FooterComponent and a NavbarComponent. Within the NavbarCom ...

When conducting tests, TypeScript raises an issue when comparing the values of array elements subsequent to performing a shift()

I am working with an array of strings, which was created by splitting a larger string using the `split` operation. Specifically, I am performing some tests on the first two elements of this array: var tArray = tLongString.split("_") if (tArray[0] == "local ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Error in Typescript: 'SyncClient' not found in Twilio

While working on my Ionic app, I encountered an issue every time I attempted to use the twilio-chat library in my project through npm install. The error consistently appeared in the .d.ts files. Here is how I imported it in my provider : import { Client ...

Having trouble retrieving the JSON data from the getNutrition() service method using a post request to the Nutritionix API. Just started exploring APIs and using Angular

When attempting to contact the service, this.food is recognized as a string import { Component, OnInit } from '@angular/core'; import { ClientService } from '../../services/client.service'; import { Client } from '../../models/Cli ...

The concept of recursive generics in combination with array inference

I'm struggling to develop a couple of generic recursive types to adjust the structure of existing types. I can't figure out why the sections detecting arrays and nested objects are not being activated. Any thoughts on what might be going wrong? ...

Guide to implementing a Page Object Model for improved debugging of Protractor tests

Introduction I am on a mission to streamline my e2e testing code using the Page Object Model for easier maintenance and debugging. My Approach When embarking on creating end-to-end tests with Protractor, I follow these steps to implement the Page Object ...

What are the benefits of reverting back to an Angular 1 directive instead of using an Angular 2 application

Our team has created numerous Angular 1 components and is eager to incorporate them into our Angular 2 application. However, the documentation suggests that we must downgrade the Angular 2 application in order to integrate and utilize the Angular 1 direc ...