我正在使用 angular2
和 Typescript
。我正在尝试创建一个 base class
,它可以被其他类继承,并且在基类中,注入(inject)了一个服务。到目前为止,我无法将 ajaxService
injected
正确地插入 base class
中,inherited
到 用户类别
。具体来说,当一个用户被实例化,然后 user
实例调用 save()
方法时,base class
中的以下行: return _this._ajaxService.send(options);
不起作用,因为 _ajaxService
未定义。
这是一个扩展基类
的用户类
:
import {Base} from '../utils/base';
export class User extends Base {
// properties
id = null;
email = null;
password = null;
first_name = null;
last_name = null;
constructor(source) {
_super.CopyProperties(source, this);
}
}
这是基类
:
import {Component} from 'angular2/core';
import {AjaxService} from './ajax.service';
@Component({
providers: [AjaxService]
})
export class Base {
constructor(private _ajaxService: AjaxService) { }
// methods
public static CopyProperties(source:any, target:any):void {
for(var prop in source){
if(target[prop] !== undefined){
target[prop] = source[prop];
}
else {
console.error("Cannot set undefined property: " + prop);
}
}
}
save(options) {
const _this = this;
return Promise.resolve()
.then(() => {
const className = _this.constructor.name
.toLowerCase() + 's';
const options = {
data: JSON.stringify(_this),
url: className,
action: _this.id ? 'PATCH' : 'POST';
};
debugger;
return _this._ajaxService.send(options);
});
}
}
除了 AjaxService
没有被注入(inject)基类之外,这工作正常。我想这是有道理的,因为用户正在被实例化而不是基础。
那么当 `Base 模块在另一个类上扩展时,我如何在 Base 模块
中使用 AjaxService
?
我想当我实例化用户时,调用了用户类中的构造函数,但没有调用注入(inject)服务的基类中的构造函数。
这是AjaxService
:
import {Injectable} from 'angular2/core';
@Injectable()
export class AjaxService {
// methods
send(options) {
const endpoint = options.url || "";
const action = options.action || "GET";
const data = options.data || {};
return new Promise((resolve,reject) => {
debugger;
$.ajax({
url: 'http://localhost:3000' + endpoint,
headers: {
Authentication: "",
Accept: "application/vnd.app.v1",
"Content-Type": "application/json"
},
data: data,
method: action
})
.done((response) => {
debugger;
return resolve(response);
})
.fail((err) => {
debugger;
return reject(err);
});
});
}
}
最佳答案
可以在基础中注入(inject)服务,但无论如何您都必须从 User 类中传递它。您不能从 Base 继承服务的实际实例化,因此您必须将它从 User 传递给 Base。这不是 TypeScript 的限制,而是 DI 通常工作方式的一个特性。
像这样:
class User extends Base
constructor(service: AjaxService) {
super(service);
}
如果 Base 为您实例化服务,您将无法影响 User 的实例化。这会抵消 DI 的很多好处,因为您会通过将依赖控制委托(delegate)给不同的组件来失去控制。
我知道你可能想通过在 Base 中指定它来减少代码重复,但这违背了 DI 的原则。
关于javascript - Angular2依赖注入(inject),类继承期间不注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478353/