Here is a sample code that subscribes to Http request and cancels it upon mouse click on the page. I would like to resubscribe if I perform click once again.
How can I toggle subscription? FIDDLE
export class AboutComponent implements OnInit {
constructor(private http:HttpClient){
}
flag=true;
documentclick = fromEvent(document, 'click');
private data = {
name: 'Samurai',
profession: 'Developer'
};
ngOnInit(){
let subscription:Subscription = this.getGoogle() )
.subscribe((res)=> {
console.log(res);
})
this.documentclick.subscribe( e=>{
if(this.flag){
subscription.unsubscribe();
}
else{
subscription = this.getGoogle().subscribe((res)=> {
console.log(res);
});
}
this.flag != this.flag;
});
}
getGoogle(): Observable<any> {
return this.http.get( 'https://jsonplaceholder.typicode.com/todos/1').pipe ( delay( 2000 ) )
}
}
With the above code I am able to cancel the request if I click the page within 2 seconds. But I am not able to subscribe again on clicking again.
Also, it would be great if someone could tell me if I am really cancelling the http request with unsubscribe()? Or is it just an illusion? Will the request hit the server if I unsubscribe withing 2 seconds?