12

I have extension for observable. It was working perfectly fine but now I've updated to angular 6 with typescript 2.7.2.

import { Observable } from 'rxjs/Observable';
import { BaseComponent } from './base-component';
import { Subscription } from 'rxjs/Subscription';
import { Subscribable } from 'rxjs';

declare module 'rxjs/Observable' {
    export interface Observable<T> {
        safeSubscribe<T>(this: Observable<T>, component: BaseComponent,
            next?: (value: T) => void, error?: (error: T) => void, complete?: () => void): Subscription;
    }
}


export function safeSubscribe<T>(this: Observable<T>, component: BaseComponent,
    next?: (value: T) => void, error?: (error: T) => void, complete?: () => void): Subscription {
    let sub = this.subscribe(next, error, complete);
    component.markForSafeDelete(sub);
    return sub;
}

Observable.prototype.safeSubscribe = safeSubscribe;

And this code is not working

  1. 'Observable' only refers to a type, but is being used as a value here.
  2. Property 'subscribe' does not exist on type 'Observable'.

https://www.typescriptlang.org/docs/handbook/declaration-merging.html

Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80

1 Answers1

14

When merging declarations, the specified module path must exactly match the path to the actual module.

With RxJS version 6, you will need to change your module declaration, as the internal structure has changed. From memory, it should be:

declare module 'rxjs/internal/Observable' {
    export interface Observable<T> {
        safeSubscribe<T>(this: Observable<T>, component: BaseComponent,
            next?: (value: T) => void, error?: (error: T) => void, complete?: () => void): Subscription;
    }
}

For an example, see one of the patching imports in rxjs-compat.

cartant
  • 57,105
  • 17
  • 163
  • 197
  • Thank you. Ohh... I wasted whole day yesterday, i've seen that its in internal but missed that. – Vova Bilyachat May 14 '18 at 01:18
  • 3
    In the past, declaration merging has wasted a lot of my time, too. I feel your pain. – cartant May 14 '18 at 01:19
  • @VolodymyrBilyachat Did you have any issues with it saying "safeSubscribe() is not a function"? We're trying to do something similar as you are. It compiles but at runtime it says that it's not a function. – Bohms27 Apr 26 '19 at 12:55
  • @VolodymyrBilyachat I'm assuming you're using this to do something like ... foo.pipe(...).safeSubscribe(...) ? We're trying something similar above and that's where it tells me it's not a function – Bohms27 Apr 26 '19 at 12:59
  • Yes, you can check in my blog, but there is still old source code https://www.bilyachat.com/blog/angular-automatically-unsubscribe-from – Vova Bilyachat Apr 27 '19 at 11:46