Search code examples
angulartypescriptserviceobservablehttpclient

The result doesn't show up on the local host


I want to iterate through 'cars' array

<div *ngFor="let car of cars">
    The {{ car.name }} of model {{ car.model }} has milage of {{ car.milage }}.
</div> 

So, I created a database with fields of the same values (id, name, model, milage). The database works fine with the server, so I began to link the back-end with the front-end by adding 'HttpClient' to the service.

import { Injectable } from '@angular/core';
import { Car } from './car';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TransportationService {

  constructor(private http: HttpClient) { }

  getCar(): Observable<Car[]> {
    return this.http.get<Car[]>('/cars/');
  }

I created a cars vaariable of type Cars[] in app.component.ts, but there is an error that says: Type 'Observable<Car[]>' is missing the following properties from type 'Car[]': length, pop, push, concat, and 28 more.

app.component.ts:

import { Component } from '@angular/core';
import { TransportationService } from './transportation.service';
import { Car } from './car';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  cars: Car[];

  constructor (private transportationService: TransportationService) {
    this.cars = this.transportationService.getCar()
  }

I tried changing type of car to 'any', but I can't see any result on the browser. What should I do?


Solution

  • You need to subscribe to the observable for it to begin publishing values. https://angular.io/guide/observables#subscribing Angular subscribe to observable