I have an Angular Http get request that will navigate the route to one of three routes depending on the data returned. Sample code below:
SomeComponent:
constructor(
private someService: SomeService,
private router: Router
) { }
ngOnInit() {
this.someService.getSomeData().subscribe(
() => {
console.log("getSomeData() did not route to a new link! Routing to a 3rd link");
this.router.navigate(['home']);
},
() => {
console.log("Some error occurred.");
});
SomeService:
constructor(
private router: Router,
private someOtherService: SomeOtherService
) { }
getSomeData() {
return this.someOtherService.getSomeOtherData().map(data => {
if (data === 'someValue') {
console.log("The data was 'someValue'");
this.router.navigate(['route1']);
}
else if (data == 'someOtherValue') {
console.log("The data was 'someOtherValue'");
this.router.navigate(['route2']);
}
});
}
SomeOtherService:
constructor(
private http: Http
) { }
getSomeOtherData() {
return this.http.get(this.getDataUrl) {
.map((res: Response) => {
console.log("Sending over the data back to SomeService");
let body = res.json();
return body.data;
})
.catch((err: Response) => {
console.log(err);
return Observable.throw(err);
});
}
}
The expected behavior is that after receiving the data from SomeOtherService, the Router will navigate to either route1 or route2 depending on the data (which I thought I read somewhere would stop the Observable stream? Maybe I misread). If the data doesn't match, then the Observable stream continues to SomeComponent which then navigates to home.
The actual behavior is that the Router will initially route to route1 or route2 but since the stream continues, the Router then finally routes to home.
So my question is, if you subscribe to an rxjs Observable, is there a way to cancel/unsubscribe to the Observable mid-stream? I thought that navigating to another route would cancel the observable but this didn't seem to work for me.
I tried unsubscribing within the map method with interesting(ly bad) results. I also tried looking at other Observable methods but being new to rxjs I wasn't sure which method would be most appropriate (I'm really only familiar with map, catch, mapTo, and (sort of) switchMap at this point).
this.http.get, then that observable terminates automatically when the response is returned. No need to cancel it. - DeborahK