简体   繁体   中英

How to unscribe from a subscription using a condition in angular 4

How do I unsubscribe to a subscription with a condition in typescript.

I subscribed to a $http.get method in Angular4, now I want to unsubscribe after received "no_more_data" from the server. Please let me know how to do it.

All the methods that I know like takeuntil, takewhile etc are not available on this Observable

getFiles(): any {
    return http.post
}

getFiles(). // here no takeWhile and takeUntil are getring allowed then how do I unsubscribe.

You can use the takeWhile operator to make the stream close automatically when "no_more_data" arrives:

$http.get(...)
.map(...)
.takeWhile((e) => e != "no_more_data")
.subscribe(...)

See also takeWhile

There're a few things here:

First, the observable that comes from Http in Angular makes a single Http request, so, no need to unsubscribe if it's just a single Http call, unless you are triggering it from something else that is repeated of course.

Second, the part that you mention, return http.post is obviously incomplete. I don't know whether this is just for posting in the question or your real code is like that. Your problem might be that you are returning the function http.post instead of calling it.

Check if your real code 1) calls the method http.post( /*some arguments here /*) , and of course 2) does return the result of that call. Hover over your method that calls http.post() to ensure the return type is an Observable .

Finally, another potential small gotcha if you are unable to find the takeWhile or takeUntil still, is that it might simply be not imported. You might need to add import 'rxjs/add/operator/takeWhile or `'rxjs/add/operator/takeUntil`` to the beginning of the file that uses it.

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