3

In Angular 2 RC 4 I have a class HttpLoading which extends the original Http of Angular2

I was able to use that in bootstrap without any issue using the below 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));

My DefaultRequest Options class

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'
    });
}

My HttpLoading Class looks like this:

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);
    }
}

With RC 5 I am not sure how do I migrate this portion of the code to NgModule providers list.

I have followed the migration guide and updated my NgModule to the following:

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 { }

But it still seems that its not properly added because in my component when I use http its still hitting the default http instead of my custom http service.

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) => {

            });
    }
}

Can anyone please guide?

0

3 Answers 3

5

Since >=RC5 now you bootstrap an @NgModule class instead of your root componenet like this, read more on this RC4 => RC5 transition guide.

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your reply. I have already followed this migration guide and I have done almost what you have mentioned in your answer but still not success. I have updated my question with my NgModule and the component can you please have a look and guide what exactly is wrong?
But it still seems that its not properly added because in my component when I use http its still hitting the default http instead of my custom http service. I'm not sure, what it means. Can you explain ?
Actually I am receiving this error "Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null"
Almost certainly it's not caused by changing the above code, it is coming from some other peice of code, which you can trace in console by expanding the error and looking at the source, if not I would suggest you to create a new question with relevant code and screenshot of the error. best
Its actually not working, the get method in HttpLoading gets called (i confirmed it through log) but the request isn't sent( the Network logs doesnt show any activity) and the Console show error "Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null". I added my DefaultRequestOptions to my question can you please have a look and see if there is something wrong with that?
|
2

Thank you so much everyone for your help, I was able to resolve the issue by removing

{ provide: RequestOptions, useClass: DefaultRequestOptions },

Which seems to be unnecassary with RC 5.

Comments

1

I hade the same issue ... setting body to empty string solved it.

so get can receive a second parameter a "RequestOptions" ... be sure to set the body property to ''

Like so ...

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.