mon*_*nie 11 javascript dependency-injection typescript angular
我使用的是angular2
带Typescript
.我正在尝试创建一个base class
可以由其他类继承的基类,并注入一个服务.到目前为止,我无法ajaxService
injected
正确地进入base class
正在inherited
进入的状态user class
.具体而言,当用户被实例化,然后save()
方法从被呼叫user
例如,在下面的行base class
:return _this._ajaxService.send(options);
不起作用,因为_ajaxService
是未定义的.
这是一个user class
扩展base class
:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是base class
:
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
除了AjaxService
没有注入基类之外,这种方法很好.我想这是有道理的,因为用户被实例化而不是基础.
那么,如何可以使用AjaxService
中Base module
时,当'基地模块正在扩展另一个类?
我想当我实例化用户时,会调用用户类中的构造函数,但是不会调用注入服务的基类中的构造函数.
这是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);
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
可以在基础中注入服务,但无论如何都必须从User类传入它.您无法从Base继承服务的实际实例化,因此您必须将其从User传递给Base.这不是TypeScript的限制,而是DI一般工作方式的一个特征.
像这样的东西:
class User extends Base
constructor(service: AjaxService) {
super(service);
}
Run Code Online (Sandbox Code Playgroud)
如果Base为您实例化了该服务,则无法影响User的实例化.这将否定DI总体上的许多好处,因为您将通过将依赖关系控制委派给不同的组件而失去控制权.
我知道你可能试图通过在Base中指定这个来减少代码重复,但这违背了DI的原则.
Angular 2 中您想要注入的每个类都必须进行注释。如果不是组件,则必须用@Injectable()
annotation对其进行注释。如果您注入的类已经注入了其他类,则必须为其创建提供程序。
import {Injectable} from 'angular2/core';
import {Base} from './base';
@Injectable()
export class User extends Base {
}
Run Code Online (Sandbox Code Playgroud)
我为你创建了 Plunker,希望它能解决你的问题:
http://plnkr.co/edit/p4o6w9GjWZWGfzA6cv41?p=preview
(查看控制台输出)
附言。请使用 Observable 而不是 Promise
归档时间: |
|
查看次数: |
2248 次 |
最近记录: |