如何在TypeScript中扩展类?

前端之家收集整理的这篇文章主要介绍了如何在TypeScript中扩展类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个服务,里面有相同的代码
  1. constructor (private http: Http) {
  2. //use XHR object
  3. let _build = (<any> http)._backend._browserXHR.build;
  4. (<any> http)._backend._browserXHR.build = () => {
  5. let _xhr = _build();
  6. _xhr.withCredentials = true;
  7. return _xhr;
  8. };
  9. }

我想将代码移到单独的文件http_base_clas.ts并尽可能地重用代码.这里是http_base_clas.ts:

  1. import {Http} from '@angular/http';
  2.  
  3. export class HttpBaseClass {
  4. constructor ( http: Http) {
  5. //use XHR object
  6. let _build = (<any> http)._backend._browserXHR.build;
  7. (<any> http)._backend._browserXHR.build = () => {
  8. let _xhr = _build();
  9. _xhr.withCredentials = true;
  10. return _xhr;
  11. };
  12. }
  13. }

如何将http_base_class扩展为auth_service.ts?

  1. import {Injectable} from '@angular/core';
  2. import {Http,Response} from '@angular/http';
  3. import {Headers,RequestOptions} from '@angular/http';
  4. import {Observable} from 'rxjs/Observable';
  5.  
  6. @Injectable ()
  7.  
  8. export class AuthenticationService {
  9. result: {
  10. ok: boolean;
  11. };
  12. private verifyUrl = 'http:example.com;
  13.  
  14. constructor (private http: Http) {
  15.  
  16. }
  17. private authRequest (url) {
  18. let body = JSON.stringify({});
  19. let headers = new Headers({ 'Content-Type': 'application/json'});
  20. let options = new RequestOptions({
  21. headers: headers
  22. });
  23. return this.http.post(url,body,options)
  24. .map((res: Response) => res.json())
  25. .map(res => {
  26. this.result = res;
  27. return this.result.ok;
  28. });
  29. }
  30. }
  1. class AuthenticationService extends HttpBaseClass {
  2. constructor(http:Http) {
  3. super(http);
  4. }
  5.  
  6. private authRequest (url) {
  7. ...
  8. }
  9. }

猜你在找的Angularjs相关文章