i have this service to get data from the api and save it into arrays afterwards:
export class DataService {
constructor(private http: HttpClient) { }
readonly baseURL = "https://localhost:44302/api";
books: Book[];
users: User[];
cards: Card[];
postId: number;
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
getBooks() {
return this.http.get(this.baseURL + '/books');
}
getCards() {
return this.http.get(this.baseURL + '/cards');
}
getUsers() {
return this.http.get(this.baseURL + '/users');
}
getData() {
const observableList: Observable<any>[] = [];
observableList.push(this.getBooks());
observableList.push(this.getUsers());
observableList.push(this.getCards());
forkJoin(observableList).subscribe(resultList => {
this.books = resultList[0] as Book[];
this.users = resultList[1] as User[];
this.cards = resultList[2] as Card[];
});
}
in my component, i run the getData method and try to console.log the data but it keeps saying that the data is undefined, even though the api data shows up in the debugging-network tab:
export class MainComponent implements OnInit {
books: Book[];
users: User[];
cards: Card[];
selectedBook: Book;
display: boolean = false;
selectedUser: User;
constructor(public dataService: DataService) { }
ngOnInit() {
this.dataService.getData();
//Save data in local component arrays
this.books = this.dataService.books;
this.users = this.dataService.users;
this.cards = this.dataService.cards;
console.log(this.books); // ==> "undefined"
}
return forkJoin(observableList);"and on my component i say: ` this.dataService.getData.subscribe((result) => { this.books = resultList[0] as Book[]; this.users = resultList[1] as User[]; this.cards = resultList[2] as Card[]; }`