1

First Angular app running Angular 5.

I am running an http get against my web server. Here's the code:

  loadSettings() {
    console.log("loadSettings() from:" + this.pizzaSettingsUrl);
    this.http.get<string[]>(this.pizzaSettingsUrl, {headers: this.headers})
      .pipe(
        tap(settings => this.processSettingsDictionary(settings)),
        catchError(this.handleError("pizzaSettings", {}))
      );
  }

  processSettingsDictionary(settings) {
    console.log("processSettingsDictionary()");
    console.log(JSON.stringify(settings));
    this.drinks = settings.drinkType;
    this.drinkSizes = settings.drinkSize;
    this.pizzaSizes = settings.pizzaSize;
    this.breads = settings.sandwichBreadType;
    this.sides = settings.sideType;
    this.toppings = settings.topping;
  }

The log "loadSettings() from:" is running with the correct url. When I copy and paste the URl from the console into a curl and run it it hits my webserver.

The this.http.get, however, is not hitting my server and I'm not getting any errors in the log. There's also nothing on my network tab indicating anything went out.

Can you see what I'm doing wrong?

Thom
  • 14,013
  • 25
  • 105
  • 185

2 Answers2

2

HttpClient only run when you subscribe to it.

 this.http.get<string[]>(this.pizzaSettingsUrl, {headers: this.headers}).subscribe();
Leandro Lima
  • 1,164
  • 6
  • 12
  • Although this is correct, I can add that `.subscribe()` isn't necessary if you're binding the data to a template where you use the `async` pipe as it will auto subscribe and unsubscribe for you. – Daniel B Jan 24 '18 at 15:31
  • OMG! Thanks for the assist. – Thom Jan 24 '18 at 15:38
1

Observables will not emit until they are subscribed to. Typically you will subscribe in whatever code calls loadSettings. For example:

// Service code
loadSettings() {
  return this.http.get<string[]>(this.pizzaSettingsUrl, {headers: this.headers})
  .pipe(
    catchError(this.handleError("pizzaSettings", {}))
  );
}

// Component code
this.pizzaService.loadSettings().subscribe(({ drink, pizzaSlices, etc }) => {
  this.drink = drink;
  this.pizzaSlices = pizzaSlices;
  this.etc = etc;
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405