I have few services ,which have the same code inside:
constructor (private http: Http) {
//use XHR object
let _build = (<any> http)._backend._browserXHR.build;
(<any> http)._backend._browserXHR.build = () => {
let _xhr = _build();
_xhr.withCredentials = true;
return _xhr;
};
}
I wanted to move the code to separate file http_base_clas.ts and to reuse code as much as possible.Here is http_base_clas.ts:
import {Http} from '@angular/http';
export class HttpBaseClass {
constructor ( http: Http) {
//use XHR object
let _build = (<any> http)._backend._browserXHR.build;
(<any> http)._backend._browserXHR.build = () => {
let _xhr = _build();
_xhr.withCredentials = true;
return _xhr;
};
}
}
How to extend http_base_class into auth_service.ts?
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
@Injectable ()
export class AuthenticationService {
result: {
ok: boolean;
};
private verifyUrl = 'http:example.com;
constructor (private http: Http) {
}
private authRequest (url) {
let body = JSON.stringify({});
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({
headers: headers
});
return this.http.post(url, body, options)
.map((res: Response) => res.json())
.map(res => {
this.result = res;
return this.result.ok;
});
}
}
In TypeScript, interfaces can also extend classes, but only in a way that involves inheritance. When an interface extends a class, the interface includes all class members (public and private), but without the class' implementations.
In TypeScript, we can't inherit or extend from more than one class, but Mixins helps us to get around that. Mixins create partial classes that we can combine to form a single class that contains all the methods and properties from the partial classes.
Definition and Usage The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
To extend types in TypeScript, we can use the extends keyword. to create the UserEvent interface that extends the Event type. We extend it by adding the string UserId field in UserEvent and inheriting the rest from Event .
class AuthenticationService extends HttpBaseClass {
constructor(http:Http) {
super(http);
}
private authRequest (url) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With