Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend http class and access custom properties (Angular2 typescript)

I created CustomHttp class which extends Http like here: http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/#comment-83563

I added providers to bootstrap like this:

bootstrap([
    HTTP_PROVIDERS,
    { provide:Http,
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, errorNotifier: NotificationHandlerService, 
                     authService: AuthInfoService) => {
            return new CustomHttp(backend, defaultOptions, errorNotifier, authService);
        },
        deps: [ XHRBackend, RequestOptions, NotificationHandlerService,  AuthInfoService]
    },
  ])

All overriden methods(get, post, etc.) work fine. Then I added custom property and method to CustomHttp class and tried to access the property outside CustomHttp:

@Injectable()
export class CustomHttp extends Http {

...
private myCustomProperty = 'It`s custom';

public getCustomProperty() {
    return this.myCustomProperty;
}
...

}

=====================

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

export class MainComponent {

    constructor(private _http: Http) {
       this._http.getCustomProperty(); // this method doesn`t exist in Http
    }
}

How can I access custom methods and properties of CustomHttp?

like image 868
norweny Avatar asked May 26 '26 03:05

norweny


1 Answers

You could try the following by casting the Http instance to CustomHttp:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { CustomHttp } from './custom.http';

@Injectable()
export class BooksService {

  constructor(private http:Http) {
    console.log((<CustomHttp>this.http).someProperty);
  }

  (...)
}

with the following CustomHttp class:

@Injectable()
export class CustomHttp extends Http {
  someProperty:string = 'some string';

  (...)
}
like image 89
Thierry Templier Avatar answered May 28 '26 16:05

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!