【发布时间】:2016-05-10 15:11:15
【问题描述】:
我正在尝试使用其他服务可以继承 n Angularjs 的方法和属性创建一个抽象类服务。使用 typescripts 扩展方法将不起作用,或者如果做得正确我不会,所以尝试使用这种模式,但遗憾的是它也不起作用。 Typescript 不知道从原型继承中继承的方法。他们有任何解决方法或解决方案吗,谢谢您的帮助
抽象服务类的示例代码
'use strict';
namespace Data {
export interface IAbstractRepository {
sayHellow(): string;
}
class AbstractRepository implements IAbstractRepository{
static extend = function (repoCtor): void {
repoCtor.prototype = new AbstractRepository();
repoCtor.prototype.constructor = repoCtor;
};
sayHellow(): string {
return 'Hello world';
}
}
function factory(): IAbstractRepository {
return AbstractRepository;
}
angular.module('core').factory('AbstractRepository', factory);
}
对于子服务类
'use strict';
namespace Data{
class BookRepository {
constructor(AbstractRepository) {
AbstractRepository.extend(this);
}
getAllBooks(): string {
// this shows as an error now it cant know that its inherited
return this.sayHellow();
}
}
factory.$inject = ['AbstractRepository'];
function factory(AbstractRepository): any {
return new BookRepository(AbstractRepository);
}
angular.module('core').factory('BookRepository', factory);
}
对于提出的解决方案,将 JshintRC 的标志降低以抑制 Typescript 产生的警告 "validthis": true and "shadow": "false
【问题讨论】:
-
能否详细说明
"Using typescripts extend method would not work",不工作是什么意思?还有"Typescript does not know the inherited methods from the prototypal inheritance",你能举个例子吗? -
在原型继承情况下,编译器将超级方法显示为子类中的错误“带有消息的红色波浪线:类中不存在错误方法”。在使用扩展类型脚本继承的情况下,我忘记了发生了什么,但我记得 jslint 和 jshint 丢失了它,原因是命名空间或模块重新定义了 ifi 和其他错误。我会尝试再次使用 Typescripts 的方式来记录错误。
标签: javascript angularjs inheritance typescript prototypal