“angular2”:“2.0.0-beta.17”,
我希望能够在import { Http, Response } from 'angular2/http';
中Base
并在子课程中使用http
。
有没有办法实现这个目标?
P.S。我不是在寻找一个“干净”的解决方案,黑客攻击,解决方法,欢迎这样的事情
基类:
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) {
}
}
答案 0 :(得分:2)
Angular2不支持使用父类来定义子类的依赖注入。
如果您想在父类中使用http
实例,那么您可以在这里做唯一的事情:
@Injectable()
export class LoginService extends ApiServiceBase {
constructor (http:Http) {
super(http);
}
(...)
}
修改强>
解决方法包括定义自定义装饰器以设置依赖注入的元数据:
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);
}
}
它将利用父构造函数中的元数据而不是自己的元数据。您可以在子类上使用它:
@Injectable()
export class BaseService {
constructor(protected http:Http) {
}
}
@CustomInjectable()
export class TestService extends BaseService {
constructor() {
super(arguments);
}
test() {
console.log('http = '+this.http);
}
}
请参阅此plunkr:https://plnkr.co/edit/DIMyUB6rCE5d78dPlPZB?p=preview。