2
I am trying to load a list on screen in my browser using Observable, however I am not succeeding, this is record that exists in my url;
This is the class of services
import { Http } from '@angular/http';
import { environment } from './../../environments/environment';
import { Restaurant } from './restaurant.model';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class RestaurantService {
public url: String = 'http://localhost:3000/api/';
constructor(private http: Http) {
// this.url = environment.url;
}
restaurants(): Observable<Restaurant[]> {
return this.http.get(`${this.url}/restaurants`)
.map(response => response.json())
}
I performed a test in component class using console.log as you can see below;
export class RestaurantsComponent implements OnInit {
restaurants: Restaurant[]
constructor(private restaurantService: RestaurantService){}
ngOnInit() {
this.restaurantService.restaurants()
.subscribe(restaurants => {
console.log('o valor é ' , this.restaurants = this.restaurants);
})
}
And the result is being that;
o valor é undefined
I wonder what I’m doing wrong?
Nice, Philip, good explanation. take away a doubt if possible. When the return of the subscribe brings a complex object to feed my property which is also of a complex type (Object) do I need to realize the instantiation of it before receiving the value? I say this because when I interpolate one of the properties of the object I declared and start the server it always returns to me saying that the object is undefined. You would know why that?
– Gonzaga Neto
Maybe you have already done it, but if you can open a question and send the link here, I could check for you @Joséluizgonzaganeto
– Philip Developer