3

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?

2 Answers 2

5

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

  (...)
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works, thank you! Is it a good way to use CustomHttp like this?
You're welcome! I don't know exactly your use case, but generally, we try to "hide" the subclass against the Http one... That being said, it's not false to do that.
0
import {Http} from '@angular/http';
import {CustomHttp} from '/path';

export class MainComponent {

    constructor(private _http: CustomHttp) {
       this._http.getCustomProperty(); 
    }
}

1 Comment

Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.