I am fairly new to TypeScript and RxJS, so my understanding of observables and subscriptions are limited.
I am required to call a method from the service class that returns an object array (for now, it is being logged to the console), and I am to make this call in the component class after a button is clicked.
The problem that I am running into is that the array is returning as empty in the console when I try to assign it to a variable. However, when I log the result from the http.get method directly, I see my object array.
I was wondering what I'm overlooking here to get this sort of error, and what can I do to fix it so as to avoid running into this again?
cars.model.ts
export interface ICar {
Make: string;
Model: string;
Year: string;
Specifications: boolean[];
}
cars.new.mock.json
[
{
"Make": "Honda",
"Model": "CRV",
"Year": "2021",
"Specifications": [
true,
true,
false,
true,
false
]
},
{
"Make": "Toyota",
"Model": "Camry",
"Year": "2021",
"Specifications": [
true,
true,
false,
true,
false
]
}
]
app.component.html
<h1>{{title}}</h1>
<button (click)="shownewCars()">New Cars</button>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { CarsService } from './services/cars.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'AutoZone';
constructor(private carsService: CarsService){
}
ngOnInit(): void {
}
shownewCars(){
this.carsService.logNewCarsMessage();
console.log(this.carsService.returnNewCars());
}
}
cars.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from "@angular/core";
import { ICar } from '../models/cars.model';
@Injectable({
providedIn: 'root'
})
export class CarsService{
carsURL = '/assets/cars.mock.json';
newCarsURL = '/assets/cars.new.mock.json'
private newCars: ICar[] = [];
constructor(private http : HttpClient){}
returnNewCars(): ICar[]{
this.http.get<ICar[]>(this.newCarsURL).subscribe(result => {this.newCars = result});
return this.newCars;
}
logNewCarsMessage(){
this.http.get(this.newCarsURL).subscribe((responseData) => console.log("Console log New Cars: ", responseData));
}
}
Console
[]
Console log New Cars: (2)[{...}, {...}]