user10157350
user10157350

Reputation:

Angular 6 pass value from one service to another?

I'm trying to use latitude and longitude from the geolocation service in my list service. Unfortunately this keeps returning as undefined. Not really sure what the issue could be.

list.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from 'rxjs';
import { List } from '../models/list.model';
import { map } from 'rxjs/operators';
import { GeolocationService } from '../services/geolocation.service';

@Injectable()
export class ListService {

    constructor(private http: Http, private geoServ: GeolocationService) { }

    getLongitude() {
        this.geoServ.getLongitude().subscribe((longitude) => {
            console.log(longitude)
        });
    }

    private serverApi = 'http://localhost:3000';



    public getAllLists(): Observable<List[]> {

        const URI = `${this.serverApi}/yelp/${longitude}/${latitude}`;

        return this.http.get(URI)
            .pipe(map(res => res.json()))
            .pipe(map(res => <List[]>res.businesses));


    }
}

geolocation.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class GeolocationService {

  constructor() { }

  getGeoLocation() {
    console.log('Geolocation working!');
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };
    const success = (pos) => {
      const crd = pos.coords;
      console.log(`Latitude : ${crd.latitude}`);
      console.log(`Longitude : ${crd.longitude}`);
    };
    const error = (err) => {
      console.warn(`ERROR(${err.code}): ${err.message}`);
    };
    navigator.geolocation.getCurrentPosition(success, error, options);
  }


  getLongitude() {
    console.log('Geolocation working!');
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };
    const success = (pos) => {
      const crd = pos.coords;
      console.log(`Longitude : ${crd.longitude}`);
      const longitude = crd.longitude;
      return longitude;
    };
    const error = (err) => {
      console.warn(`ERROR(${err.code}): ${err.message}`);
    };
    navigator.geolocation.getCurrentPosition(success, error, options);
  }
}

thank you for taking the time to look at this. And I appreciate the further help on my additional question below. text text text text won't let me post until I add more details text text text text.

Upvotes: 1

Views: 369

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71901

You are not returning anything from your methods. You should use a return statement. You also need to use either a callback function a promise or a observable. I'll give you a observable example:

getLongitude() {
  this.geoServ.getLongitude().subscribe((longitude) => {
    console.log(longitude)
  });
}

And change your getLongitude:

getLongitude() {
  return new Observable((observer) => {
    console.log('Geolocation working!');
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };
    const success = (pos) => {
      const crd = pos.coords;
      console.log(`Longitude : ${crd.longitude}`);
      const longitude = crd.longitude;
      observer.next(longitude);
      observer.complete();
    };
    const error = (err) => {
      console.warn(`ERROR(${err.code}): ${err.message}`);
      observer.error(err);
      observer.complete();
    };
    navigator.geolocation.getCurrentPosition(success, error, options);
  });  
}

If you want to get the longitude and latitude in your getAllList method you can use the mergeMap operator:

public getAllLists(): Observable<List[]> {
  return this.geoServ.getGeoLocation().pipe(
    mergeMap(({ latitude, longitude}) => 
      this.http.get(`${this.serverApi}/yelp/${longitude}/${latitude}`)
    ),
    map(res => res.businesses)
  );
}

I'm using the HttpClient here. This is the 'new' http module from angular. It's advised to use this one instead of the old one. It also automatically does the json() call for you.

Upvotes: 1

Related Questions