Angular2使用从基类导入的库 [英] Angular2 use imported libs from base class

查看:111
本文介绍了Angular2使用从基类导入的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"angular2":"2.0.0-beta.17",

"angular2": "2.0.0-beta.17",

我希望能够在我的Base中使用import { Http, Response } from 'angular2/http';并在子类中使用http.

I'd like to be able to import { Http, Response } from 'angular2/http'; in my Base and use http in the child classes.

有没有办法做到这一点?

Is there a way to achieve this ?

P.S.我不是在寻找一种干净"的解决方案,欢迎黑客,变通办法和类似的事情

P.S. I'm not looking for a "clean" solution, hacks, workarounds and things like this are welcome

基类:

import { Http, Response } from 'angular2/http';

export class ServiceBase {
  constructor (private http: Http) {}

}

还有一个子班:

import { ApiServiceBase } from '../../api-service-base';
import { Injectable }     from 'angular2/core';
// import { Http, Response } from 'angular2/http';
import { AuthUser }       from './auth_user';
import { Observable }     from 'rxjs/Observable';
import { Headers, RequestOptions } from 'angular2/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class LoginService extends ApiServiceBase {
  constructor () {
    super();
  }
  private url = 'http://localhost:8080/api/signin';

  login (user: AuthUser): Promise<AuthUser> {
    let body = JSON.stringify(user);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, body, options)
               .toPromise()
               .then(this.extractData)
               .catch(this.handleError);
  }

  private extractData(res: Response) {
    console.log(res);
    if (res.status < 200 || res.status >= 300) {
      throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: any) {
  }
}

推荐答案

Angular2不支持使用父类定义子类的依赖项注入.

Using a parent class to define dependency injection of sub classes isn't supported in Angular2.

如果要在父类中使用http实例,则只能在此处执行以下操作:

The only thing you can do here if you want to use the http instance in the parent class:

@Injectable()
export class LoginService extends ApiServiceBase {
  constructor (http:Http) {
    super(http);
  }

  (...)
}

修改

一种解决方法是定义一个自定义装饰器,以设置用于依赖项注入的元数据:

A workaround would consist of defining a custom decorator to set the metadata for dependency injection:

export function CustomInjectable(annotation: any) {
  return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);

    Reflect.defineMetadata('design:paramtypes', parentAnnotations, target);
  }
}

它将利用来自父构造函数的元数据,而不是其自身的元数据.您可以在子类上使用它:

It will leverage the metadata from the parent constructor instead of its own ones. You can use it on the child class:

@Injectable()
export class BaseService {
  constructor(protected http:Http) {
  }
}

@CustomInjectable()
export class TestService extends BaseService {
  constructor() {
    super(arguments);
  }

  test() {
    console.log('http = '+this.http);
  }
}

查看此插件: https://plnkr.co/edit/DIMyUB6rCE5d78dPlPZB?p=preview .

这篇关于Angular2使用从基类导入的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆