'Observable' is not a class derived from 'Observable'

前端 未结 9 2450
灰色年华
灰色年华 2020-12-29 18:11

When trying to extend a class from a class in a node_modules the typescript compiler throws a error saying:

Property \'source\' is protected but

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 18:50

    I got same issue.

    I have following catalog structure (angular2 project)

    angular
    |
    ---- common_files
          |
          ----- package.json
          |
          ----- index.ts
          |
          ----- catalog1
                |
                ---- package.json
                |
                ---- some_file_with_service_model_comopnent.ts
                |
                ---- index.ts    - this is regular barrel file
          |
          ----- catalog2
    |
    ---- app1
         |
         ------ package.json
    |
    ---- apps
         |
         ------ package.json
    

    In my common I have definied objects and services:

    export class ItemBase {}
    
    esport class SomeType extends ItemBase {}
    
    export class ItemServiceBase {
        public getItems():Observable {
             //do something
        }
    }
    
    export class SomeService extends ItemServiceBase {
        //some specific operations can go here
    }
    

    In my apps I was using items from common as follows:

    import { SomeType, SomeTypeService } from "warehouse-system/products-settings";
    
    class AttributeTypesComponent {
      private myValues : Observable;
      private service : SomeTypeService;
    
      constructor(){
          this.service = new SomeTypeService();
          this.myValues = > this.service.getItems();
      }
    }
    

    This were causing compilation issues: ERROR in [at-loader] src/app/some_file.ts:22:47 Type 'Observable' cannot be converted to type 'Observable'. Property 'source' is protected but type 'Observable' is not a class derived from 'Observable'.

    After investigation I changed type of myValues but it still doesn't solve problem. Compilation issues changed to:

    ERROR in [at-loader] src/app/some_file.ts:22:47 Type 'Observable' cannot be converted to type 'Observable'. Property 'source' is protected but type 'Observable' is not a class derived from 'Observable'.

    The final solution (workaround)

    What solved my problem, was "rewriting" observable on the app side:

        this.myValues = Observable.create(subscriber => {
          this.service.getItems().subscribe(items => subscriber.next(items));
        });
    

    This is not really nice way to solve it. In my opinion this problem is caused by a bug in npm/typescript/observables. But untill the problem is not solved on the typescript devs side, you can use this workaround as solution.

提交回复
热议问题