Utilizing HTTP calls to my Web API to fetch 2 API keys for accessing another API.
These API keys are fetched using 2 functions:
getApiKey()
and getAppId()
Upon calling these functions within the constructor, the returned value, stored in a global variable, appears as undefined.
However, if I call them outside the constructor, everything functions correctly.
I prefer not to rely on global variables. Even when attempting to create a variable inside the getApiKey()
or getAppid()
function and assign it within the http.get call, the outcome still remains undefined.
It seems the issue lies in the asynchronous nature of http.get
, but I am unsure how to address this and make it wait for the response.
Below is the provided code snippet:
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) => {
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) => {
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) => {
this.matchesList = res.json().matches;
console.log(this.matchesList);
if(this.matchesList.length == 0){
this.notFoundError = true;
}
else{
this.notFoundError = false;
}
},
(err) => {
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) => {
this.matchesList = res.json().matches;
this.notFoundError = false;
},
(err) => {
if(err.status == 400){
// Bad Request
}
else if(err.status == 409){
// API Rate Limit Exceeded
}
else if(err.status == 500){
// Internal Server Error
}
});
}
}