简体   繁体   中英

Rxjs / AngularFire2: unsubscribe(): “TypeError: Illegal Invocation”

I get an error "Illegal Invocation" when I try to unsubscribe from within this rxjs observer.

let s = names.subscribe((a:Array<any>) => {
    s.unsubscribe();
    if(a.length){ reject('name exists') }
}

The names variable is of type FirebaseListObservable

Setting some breakpoints, i can see that the observer function (callback) is being called immediately. Any code following this subscription is run AFTER the callback has already run once. The s variable is undefined, therefore, within the callback.

What am i doing wrong here? Shouldnt the observable wait till next tick? Should i do it manually?

UPDATE: wrapping the callback code in a setTimeout( code , 0) got rid of the error. It seems strange that I should have to do this though?

When the next block gets executed is completely implementation dependent. The point of having a callback is that your code shouldn't have to concern itself with when the event arrives, only what should happen when it does.

If you need only the first item from the stream then you could use either take(1) or first() instead:

let s = names.first().subscribe((a:Array<any>) => {
    if(a.length){ reject('name exists') }
}

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