Observable returning undefined

2

I'm trying to load a list on screen in my browser using Observable, however I'm not having success, this is a record that exists in my url;

This is the service class

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 on the 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 this;

o valor é  undefined

What am I doing wrong?

    
asked by anonymous 29.06.2018 / 13:38

3 answers

3

The problem is that you are using this twice. this.restaurants! = restaurants

.subscribe(restaurants => {
    this.restaurants =restaurants 
    console.log('o valor é ' , this.restaurants);
})
    
29.06.2018 / 13:42
2

True friend, you had a logic ai error, then try to pass the value returned from restaurants to your variable this.restaurants in your subscriber.

So your output undefined refers to the Watch of the javascript of a variable that is not being defined in loop of subscriber . It is being iterated over an undefined value, resulting in something that is not being set.

We solve the case using the arrow function of the correct way

this.restaurants = restaurants

    
29.06.2018 / 14:43
1

The problem is that you are adding the component's scope variable to itself. You have to add the response of API to variable restaurants .

I modified your method to get a little clearer.

Wrong - > this.restaurants = this.restaurants

export class RestaurantsComponent implements OnInit {

  restaurants: Restaurant[]

  constructor(private restaurantService: RestaurantService){}

  ngOnInit() {
    this.restaurantService.restaurants()
       .subscribe(resposta => this.restaurants = resposta);
    })
  }
    
29.06.2018 / 15:23