Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - chaining observable subscribes

Tags:

angular

I am building my first Angular 2 app and am having a problem chaining observable subscribes.

The below code works well in Chrome but not in Firefox and IE.

What is the correct way to do the below? I need to get the current location of the user then pass this into a second call (getTiles).

I'm not seeing any errors in the web dev browser tools. This is also when I run on localhost. The site isn't deployed yet. I'm not sure if that could be related.

I'm using Angular 2.0.0-rc.2.

ngOnInit(): void {

       this._LocationService.getLocation().subscribe(
           location => {this.location = location;

                    // make the next call using the result of the first observable 
                   this._TilesService.getTiles(0, location).subscribe(
                        tiles => {this.tiles = tiles; this.index = 1;},
                        error =>  this.errorMessage = <any>error);                
            });    
}  

Here is the location service...

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';

import { ILocation } from '../interfaces/location';

@Injectable()
export class LocationService {

    constructor() { }

    getLocation(): Observable<ILocation> {

      let locationObservable = new Observable<ILocation>((observer: Observer<ILocation>) => {

            if (navigator.geolocation) {

                var positionOptions = {
                    enableHighAccuracy: false,
                    timeout: 1000,
                    maximumAge: 5000
                };

                navigator.geolocation.getCurrentPosition(function (position) {

                    var location: ILocation = {
                        Longitude: position.coords.longitude,
                        Latitude: position.coords.latitude
                    };

                    observer.next(location);
                }, this.locationErrorHandler, positionOptions);
            }
        });

        return locationObservable;
    }

   locationErrorHandler(error:any) { }
}

Here is the getTiles service...

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { ITile } from '../interfaces/tile';
import { ILocation } from '../interfaces/location';

@Injectable()
export class TilesService {

    constructor(private _http: Http) { }

    getTiles(index: number, location: ILocation): Observable<ITile[]> {  
      this._tileUrl = 'SOME URL';

      return this._http.get(this._tileUrl)
            .map((response: Response) => <ITile[]> response.json())
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}
like image 546
Ben Cameron Avatar asked Jun 23 '16 22:06

Ben Cameron


1 Answers

Your code looks correct, but in your case you can avoid nesting subscriptions by doing this...

ngOnInit(): void {

   this._LocationService.getLocation().concatMap(location => {
       this.location = location;

       // make the next call using the result of the first observable 
       return this._TilesService.getTiles(0, location);    
   }).subscribe(
       tiles => {this.tiles = tiles; this.index = 1;},
       error =>  this.errorMessage = <any>error);                
}  

concatMap (RxJS 5) is selectConcat in RxJS 4 according to https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md, I haven't use RxJS 4 though

like image 95
Can Nguyen Avatar answered Oct 06 '22 19:10

Can Nguyen