我在用着 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);
}
}
这里是 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);
});
}
}
这样可以正常工作 AjaxService
没有注入基类。我想这是有道理的,因为用户被实例化而不是基础。
那我怎么用呢 AjaxService
在里面 Base module
什么时候`Base模块正在另一个类上扩展?
我想当我实例化用户时,会调用用户类中的构造函数,但是不会调用注入服务的基类中的构造函数。
这是 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);
});
});
}
}