K
K
Konstantin2020-10-07 15:39:06
OOP
Konstantin, 2020-10-07 15:39:06

How to use the principle of polymorphism?

There is a class and a service:

interface Search {
    search(): Observable<any>;
}

class CloudService implements Search {
    search(): Observable<any> {
        return of([1,2,3]).pipe(delay(3000));
    }
}

class SearchByAddressParcel implements Search {
    constructor(private CloudService: CloudService) {}

    search() {
        this.CloudService.search().subscribe((response) => {
          console.log(response);
        });
    }
}


Both implement the interface. interface Search {}

The problem is that SearchByAddressParcelthe search method of the class must return void, because the subscription occurs inside the method.

Tomorrow I want a new implementation: c lass SearchByAddressNew {}which should also have a search method and call the service internally.

Then make new SearchByAddressParcel().search()a substitution:new SearchByAddressNew().search();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2020-10-07
@Junart1

You can implement a generic :thinking
Either
search(): Observable<any> | void

interface Search<T> {
    search(): T
}

class CloudService implements Search<Observable<any>> {
    search() {
        return of([1,2,3]).pipe(delay(3000));
    }
}

class SearchByAddressParcel implements Search<void> {
    constructor(private CloudService: CloudService) {}

    search() {
        this.CloudService.search().subscribe((response) => {
          console.log(response);
        });
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question