简体   繁体   中英

Typescript inheritance in Angularjs 1.x

Am trying to make an abstract class service with methods and properties that other services can inherit n Angularjs. Using typescripts extend method would not work or i don't if am doing it properly, so tried using this pattern but sadly it too did not work. Typescript does not know the inherited methods from the prototypal inheritance. Is their any workaround or a solution to this, thank you for the help

example code for the Abstract service Class

'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);
}

and for the sub service class

'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);
}

for the solution proposed down the flags for JshintRC to suppress warnings produced by Typescript "validthis": true and "shadow": "false

Your question is not that clear, even with the comment you answered my question I'm still not sure what the problem is.

I'm not angular developer, so I can't answer angular specific questions, but as inheritance goes in typescript this is how you do it:

namespace Data {
    export interface IAbstractRepository {
        sayHellow(): string;
    }

    abstract class AbstractRepository implements IAbstractRepository {
        constructor() {}

        sayHellow(): string {
            return 'Hello world';
        }
    }


    class BookRepository extends AbstractRepository {
        constructor() {
            super();
        }

        getAllBooks(): string {
            return this.sayHellow();
        }
    }

    angular.module("core").factory("BookRepository", BookRepository);
}

If you'll tell me what's wrong with this, then I might be able to help you solve that.


Edit

Since the playground url is too long for the comments, here it is .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM