title: angular/ts global variable assigned in async call undefined in constructor
body: <p>I'm using HTTP calls to my Web API to retrieve 2 API keys to use another API.</p>
  
  <p>These API keys get retrieved through 2 functions: 
  <code>getApiKey()</code> and <code>getAppId()</code></p>
  
  <p>When I call those functions inside the constructor the value returned by them, which is a global variable, is undefined.</p>
  
  <p>When I call it outside of the constructor it works fine.</p>
  
  <p>I don't want to use global variables, but when I try to create a variable inside the <code>getApiKey()</code> or <code>getAppid()</code> function body and assign it inside the http.get call, it also returns undefined.</p>
  
  <p>I'm guessing this has to do with <code>http.get</code> being asynchronous, but I have no idea how to fix it/how to make it wait for the response.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>import { Component, OnInit } from '@angular/core';
  import { Http, Headers, Response, RequestOptions } from '@angular/http';
  import { Constants } from '../../utils/constants';
  import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
  
  @Component({
    selector: 'app-recipes',
    templateUrl: './recipes.component.html',
    styleUrls: ['./recipes.component.css']
  })
  export class RecipesComponent {
    appid;  
    appkey;
    matchesList;  
    recipeSearchForm: FormGroup;
    notFoundError: boolean = false;
  
    constructor(private http: Http) {
      this.searchRecipeInit();    //undefined here
  
      this.recipeSearchForm = new FormGroup({
        recipeSearchInput: new FormControl()
      });
    }
  
    getApiKey(){
      this.http.get(Constants.GET_YUMMLY_APP_KEY, this.getOptionsSimple()).subscribe((res: Response) =&gt; {  
        this.appkey = res.text();
        console.log(this.appkey);   
      });
      return this.appkey;    
    }
  
    getAppId(){
      this.http.get(Constants.GET_YUMMLY_APP_ID, this.getOptionsSimple()).subscribe((res: Response) =&gt; {  
        this.appid = res.text(); 
        console.log(this.appid);      
      });
      return this.appid;    
    } 
  
    getSearchParams(){
      // get from search text field
      var str = this.recipeSearchForm.get('recipeSearchInput').value
      // split into words and add + in between
      if(str != null) {
        var correctFormat = str.split(' ').join('+');
        return correctFormat          
      }
      return str
    }
  
    getOptions(){
      var headers = new Headers();
  
      headers.append('Content-Type', 'application/json' );    
      headers.append('X-Yummly-App-Key',this.getApiKey());    
      headers.append('X-Yummly-App-ID',this.getAppId());
  
      let options = new RequestOptions({ headers: headers });
  
      return options;
    }
  
    getOptionsSimple(){
      var headers = new Headers();
  
      headers.append('Content-Type', 'application/json' ); 
  
      let options = new RequestOptions({ headers: headers });
  
      return options;
    }
  
    searchRecipe() {     
        // not undefined here
        this.http.get(Constants.GET_SEARCH_RECIPE+this.getSearchParams(), this.getOptions()).subscribe((res: Response) =&gt; {  
          this.matchesList = res.json().matches;
  
          console.log(this.matchesList);
          if(this.matchesList.length == 0){
            this.notFoundError = true;
          }
          else{
            this.notFoundError = false;
          }
        },
        (err) =&gt; {
          if(err.status == 400){
            // Bad Request
          }
          else if(err.status == 409){
            // API Rate Limit Exceeded
          }
          else if(err.status == 500){
            // Internal Server Error
          }
        });
    }
  
    searchRecipeInit() {     
      this.http.get(Constants.GET_SEARCH_RECIPE+"", this.getOptions()).subscribe((res: Response) =&gt; {  
        this.matchesList = res.json().matches;
  
        this.notFoundError = false;      
      },
      (err) =&gt; {
        if(err.status == 400){
          // Bad Request
        }
        else if(err.status == 409){
          // API Rate Limit Exceeded
        }
        else if(err.status == 500){
          // Internal Server Error
        }
      });
  }
  }
  </code></pre>