Angular list implementation with problem

Asked

Viewed 44 times

0

I don’t understand what’s wrong with my code, the code is correct, even so I can’t list the data from my Mongodb database.

This is my HTML

<div class="col-lg-12">
  <h3>{{ title }}</h3>
<table class="table table-hover">
    <thead class="thead-default">
      <tr>
        <th>Nome</th>
        <th>Categoria</th>
        <th>Ação</th>
      </tr>
    </thead>
    <tbody>
        <tr *ngFor="let restaurant of restaurants">
          <td>{{ restaurant.name }}</td>
          <td>{{ restaurant.category }}</td>
          <td>
            <a  class="btn btn-sm btn-success">
              <span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> Ver
            </a>
            <a class="btn btn-sm btn-primary">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                Editar
            </a>
            <a  class="btn btn-sm btn-danger">
              <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Deletar
            </a>
          </td>
        </tr>
    </tbody>
</table>
</div>

This is my component class;

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '../../../../../node_modules/@angular/router';
import { RestaurantService } from '../../services/restaurant.service';
import { Restaurant } from '../../models/restaurant';

@Component({
  selector: 'mt-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {


  public title: string;
  public restaurants: Restaurant[];
  public numbers = new Array(10);
  public token;

  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _restaurantService: RestaurantService
  ) {
      this.title = 'Adicionar Restaurantes';

    }

  ngOnInit() {
    this.getRestaurants();
  }

  getRestaurants() {
    this._restaurantService.getRestaurants().subscribe(
      response => {
        if (!response.restaurants) {

        } else {
          this.restaurants = response.restaurants;
        }
      },
      error => {
        console.log(<any>error);
      }
    );
  }


}

And that’s the proof you’re listing, but the data doesn’t appear on screen;

inserir a descrição da imagem aqui

Can anyone see the problem? Please! This is the class of services;

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { environment } from 'environments/environment';


@Injectable()
export class RestaurantService {

  public url: string;


  constructor(private _http: Http) {
    this.url = environment.url;
   }




    getRestaurants(){
      return this._http.get(this.url+'/admin-painel/listas').map(res => res.json());
    }


}

My back-end is the express Node it is working on my Postman;

router.get('/admin-painel/listas', controller.get);

My list of data;

inserir a descrição da imagem aqui

  • I think your data is not in response.restaurants. Tries to give a console.log(Response) and see if it lists the data directly.

  • is as undefine, please as I do to fix?

  • @ladyband if you are giving Undefined the data is not getting there. Can you put the code of your service please?

  • I just put, could I have a look please?

  • this._restaurantService.getRestaurants().subscribe(&#xA; response => {&#xA;console.log(response) &#xA;}) try to see if you list your data.

  • I just updated my post, is coming the data, this is all very strange.

  • your JSON does not return the nested items in the restaurant tag. Try this way: response => {this.restaurants = response;}

  • @Pedro just took the if/Else, but did not fix the problem.

  • edited my comment, remove the . Restaurants after the replay

  • @Pedro picked it up, it worked perfectly, I found it strange that this might happen :) thank you very much.

  • 1

    show! I will formulate an answer explaining why the error

Show 6 more comments

1 answer

1


The problem is in its component:

 getRestaurants() {
    ...
      response => {
        if (!response.restaurants) {

        } else {
          this.restaurants = response.restaurants; 
        }
      },
   ...

Your API returns only one list, with no grouper attribute. So, when trying to get the attribute restaurants of Sponse, gives error, because the attribute does not exist.

For this method to work, your API should return the following:

"restaurants" : [
    {
      "chave" : "valor",
      "chave2" : "valor2",
    },    
    { 
      "chave2" : "valor3",
      "chave3" : "valor4",
    }   
]

There it is, the property restaurants would be available.

As a suggestion, I also recommend reversing the logic of your if. It would look like this:

getRestaurants() {
    this._restaurantService.getRestaurants().subscribe(
      response => {
        if (response) {
            this.restaurants = response;
        }
      },
      error => {
        console.log(<any>error);
      }
    );
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.