简体   繁体   中英

How to implement abstract class with abstract method in Angular

I have a perhaps trivial question, but I cannot understand how I can use the methods of an abstract class based only on calling it and choosing the correct override based on the type of value I have as Input.

For example, if I have something like this:

export abstract class Parent {
    constructor(
        public type: View
    ){}

    abstract getSource(): string | string[]
}

export class Child1 extends Parent {
    getSource(): string {
        return this.type.view1
    }
}

export class Child2 extends Parent {
    getSource(): string[] {
        return this.type.view2
    }
}

And I wanted to call the abstract class Parent, and, based on the type, figure out whether to use the function in the Child1 or Child2 class. I thought you could do it like this:

export class AngularComponent {
    public _VieweSource: string | string[];
    @Input() set data(type: View) { 
        // here i need to return Child1.getSource() or Child2.getSource()
        // not calling new Child1(type).getSource()
        // but something like this: Parent(type).getSource() --> Child1 if type.view1=string || Child2 if type.view2=string[]
    }
}

the View type are this:

{type: "simple", view1: "hello world"} || {type: "complex", view2:["hello", "world"]}

Sorry if the question is wrong, if there are any questions I can answer. Thanks in advance.

The problem is that you are trying to choose which class to use, based on the values in type . You should not try to let inheritance figure out which class to choose, a simple if statement is build for that.

export class AngularComponent {
    public _VieweSource: string | string[];
    @Input() set data(type: View) { 
        let obj: Parent;
        if (type.view1 && typeof type.view1 === 'string'){
            obj = new Child1(type);
        } else if(type.view2 && type.view2 instanceof Array){
            obj = new Child2(type);
        }
        obj.getSource();
    }
}

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