Reputation: 67
Im having issues with performing a simple get request to the backend which returns a JSON. When i perform this get request in my code it returns an observable, which i directly assign to a variable through the subscribe method. However it is only assinged and available within this method and undefined everywhere else.
The api service get method:
public getAllProcessCategories() {
return this.http.get(this.apiURL + 'typeOne=PROCESSCATEGORIES&typeTwo=PROCESSCATEGORIES');
}
The usage of the api:
import { ApiService } from './../api.service';
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ProcessCategory } from './process-category';
@Component({
selector: 'app-process-category',
templateUrl: './process-category.component.html',
styleUrls: ['./process-category.component.css']
})
export class ProcessCategoryComponent implements OnInit {
processCategories = [];
constructor(private api: ApiService) {
}
ngOnInit(): void {
this.fillProcessCategories();
this.printAfterRequest();
}
fillProcessCategories() {
this.api.getAllProcessCategories().subscribe(data => {
this.processCategories = data['entities'];
console.log(this.processCategories);
});
}
printAfterRequest() {
for (const category of this.processCategories) {
console.log(category);
}
}
}
Iknow that it is, because I want to get the result before the httpRequest is finished. So what is the best way to perform a get request in angular 4, which returns a JSON and than parse this JSON and map it to a class for use in my component?
Upvotes: 0
Views: 248
Reputation: 2943
Slightly tweak your API method to
return this.http.get(this.apiURL+ 'typeOne=PROCESSCATEGORIES&typeTwo=PROCESSCATEGORIES')
.map(res => {
return res.json();
})
.catch(this.handleError);
Then move printAfterRequest
to subscribe callback
fillProcessCategories() {
this.api.getAllProcessCategories().subscribe(data => {
this.processCategories = data['entities'];
this.printAfterRequest();
console.log(this.processCategories);
});
}
Upvotes: 1