Jeff M Palmer
Jeff M Palmer

Reputation: 67

Javascript Angular Blocking?

I have an angular function that looks for a 'list' parameter in the initial URL, and if found will go out and get information. Otherwise I want to get the geolocation. I don't want to get geolocation if the URL param is present. Am I even using the right terms?

constructor(private router: Router, private activatedRoute: ActivatedRoute, private providerService: ProviderService) { }

  ngOnInit(): void {
    this.processURL();
    this.processGPS();
  }

  private processURL() {
    console.log('1a');

    this.activatedRoute.queryParams.forEach(item => {
      if (item['list']) {
        console.log('1b');
        this.providerService.setCurrentProvider(item['list']);
      }
    });
  }

  private processGPS() {
    console.log('2a');
    window.navigator.geolocation.getCurrentPosition(position => {
      this.providerService.findByGeo(position.coords).subscribe(providers => {
        if (providers.length > 0) {
          console.log('2b');
          this.providerService.setCurrentProvider(providers[0]);
        }
      },
        () => {
          console.log('GeoLocation Not available or disabled');
        }).unsubscribe();
    });
  }

Upvotes: 0

Views: 76

Answers (2)

jeprubio
jeprubio

Reputation: 18002

Move the processGPS to an else when the list parameter is not found:

ngOnInit(): void {
    this.processURL();
}

private processURL() {
    console.log('1a');

    this.activatedRoute.queryParams.subscribe(item => {
      if (item['list']) {
        console.log('1b');
        this.providerService.setCurrentProvider(item['list']);
      } else {
        this.processGPS();
      }
    });
}

Upvotes: 1

Rob Monhemius
Rob Monhemius

Reputation: 5144

queryParams is an Observable, not an array, so you should subscribe to it.

What I did:

  • subscribe to the this.activatedRoute.queryParams
  • check if the list property exists on the parameters
    • If it does exist call some service
    • Else if it does not exist use GPS

ngOnInit(){
    this.activatedRoute.queryParams.subscribe( params => {
      if( typeof params.list !== 'undefined')
        this.providerService.setCurrentProvider( params.list );
      else
        this.processGPS();
    });
  }

Upvotes: 1

Related Questions