Angle variable only takes the object if I put it inside an * ngFor, although the function should return a single object [closed]

0

The following Javascript code works correctly:

<div *ngIf="pedido">
  <div *ngFor="let pedido of pedido"> 
    <h2>Pedido del {{ pedido.fecha | date :  "dd/MM/y" }} </h2>
    <div>
        <label>fecha:
          <input [(ngModel)]="pedido.fecha" placeholder="fecha">
        </label>
      </div>
      <div>
        <label>productos:<br />
          <textarea [(ngModel)]="pedido.productos" placeholder="productos"> </textarea> 
        </label>
      </div>
  </div>

</div>

However, if I remove the ngFor (which should not be necessary since the component should return a single object, and in fact it does), if I remove the ngFor, like this:

<div *ngIf="pedido">
  <!-- <div *ngFor="let pedido of pedido">  -->
    <h2>Pedido del {{ pedido.fecha | date :  "dd/MM/y" }} </h2>
    <div>
        <label>fecha:
          <input [(ngModel)]="pedido.fecha" placeholder="fecha">
        </label>
      </div>
      <div>
        <label>productos:<br />
          <textarea [(ngModel)]="pedido.productos" placeholder="productos"> </textarea> 
        </label>
      </div>
  <!-- </div> -->

stop returning the data of the object.

This is the code of the component that is responsible for obtaining the object:

import { Component, OnInit, Input } from '@angular/core';
import { Pedido } from '../pedido';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

import { PedidoService } from '../pedido.service';


@Component({
  selector: 'app-pedido-detalles',
  templateUrl: './pedido-detalles.component.html',
  styleUrls: ['./pedido-detalles.component.css']
})
export class PedidoDetallesComponent implements OnInit {
  @Input() pedido: Pedido;

  constructor(
    private route: ActivatedRoute,
    private pedidoService: PedidoService,
    private location: Location
  ) { }

  ngOnInit() {
    this.getPedido();
  }

  getPedido(): void {
    const id = this.route.snapshot.paramMap.get('id');
    this.pedidoService.getPedido(id)
    .subscribe(pedido => {
      console.log(JSON.stringify(pedido));
      this.pedido = pedido;
    });
  }

}

The json that I get is the following:

[{"_id":"5bd3d9f9dd79d325bbc04169","fecha":"2018-10-27T03:00:00.000Z","productos":"mix, avena,zika,chuki","__v":0}]
    
asked by Pedro 27.11.2018 в 15:46
source

1 answer

0

You could change your <div *ngIf="pedido> by <ng-container*ngIf="pedido> , in addition, as mentioned in the comments. You receive an arrangement of an element, you could change the back-end to return a json or use this.pedido = pedido[0]; .

    
answered by 27.11.2018 в 16:29