'Angular Service, no return when API is used
I am trying Angular service for the first time, and I am having trouble while I use the API in the service. When I call the regular method, I get a return value, but when I call the method that uses API, I don't get any return value.
Here's my app.component.ts file.
import { Component, OnInit } from '@angular/core;
enter code hereimport { DataService } from './data.service;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
_artists: Array<any>
_produceArray: Array<any>
title = 'APIAssignmentPartBandCVersion2';
constructor(private list: DataService) { }
ngOnInit(): void {
this._artists = this.list.getList()
this._produceArray = this.list.getProduce()
console.log(this._produceArray, "hellohello")
console.log(this._artists, "artistArray")
}
}
Here's my data.service file.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const BASE_URL = 'https://localhost:44308/api/Store/';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
_producesArray: Array<any>;
_suppliersArray: Array<any>;
_producesupplierArray: Array<any>;
_errorMessage: String = "";
getList(){
return[
{'grade':1, 'name':'Davido', 'country':'Nigeria'},
{'grade':2, 'name':'Burna Boy', 'country':'Nigeria'},
{'grade':3, 'name':'Diamondz Platinum', 'country':'Tanzania'},
{'grade':4, 'name':'Sarkodie', 'country':'Ghana'},
{'grade':5, 'name':'Mr. Eazi', 'country':'Nigeria'}
];
}
getProduce(){
this.http.get<any>(BASE_URL + "produce/").subscribe(data => {
this._producesArray = data;
this._errorMessage = data["errorMessage"];
console.log(data)
},
error =>{
this._errorMessage = JSON.stringify(error);
})
return this._producesArray
}
}
Thank you.
Solution 1:[1]
the problem is that - you call the API which is asynchronic action which means is moving on to the next line of code while this request is execute...
so you return _producesArray before it's really filled with data.
what do you need to do is simply return the observable like this:
return this.http.get<any>(BASE_URL + "produce/")
and make the subscribe inside the component
this.list.getProduce().subscribe(...)
good luck :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
