【问题标题】:JSON with name Zero [closed]名称为零的 JSON [关闭]
【发布时间】:2019-07-28 08:54:16
【问题描述】:

我正在向 JSON 服务器发出 http 请求,并将值放入变量中,当我创建 console.log() 时,它会显示来自 json 的所有信息,但是当我尝试使用插值带来模板的信息,它会抛出这个错误

ERROR TypeError: Cannot read property 'numero' of undefined

A 注意到 json 的名字是零,我该如何解决?

我的服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { API } from '../../../app.api';


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

  constructor(private http: HttpClient) { }

  recuperaDetalhes(): any{
    return this.http.get("http://localhost:4000/tarefadetalhe")

 }
}

这是我调用该服务的页面:

import { Component, OnInit } from '@angular/core';
import { NavParams } from '@ionic/angular';
import { TarefadetalheService } from './tarefadetalhe.service';
import { Tarefa } from '../../models/tarefa.model';

@Component({
  selector: 'app-tarefas-detalhe',
  templateUrl: './tarefas-detalhe.page.html',
  styleUrls: ['./tarefas-detalhe.page.scss'],
})
export class TarefasDetalhePage implements OnInit {
 idTarefa = null
 tarefa: any
  constructor(private navParams: NavParams, private getTarefaDetalhe: TarefadetalheService) { }

  ngOnInit() {
    this.idTarefa = this.navParams.get('id_tarefa');
    this.getTarefaDetalhe.recuperaDetalhes().subscribe((data)=>{
      this.tarefa = data[0] //now it works 
    })
  }
}

这是我的模板:

<ion-header>
  <ion-toolbar>
    <ion-title>{{tarefa.numero}}</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
ID da tarefa é: {{idTarefa}}
</ion-content>

正如您现在所看到的,我可以按我的意愿显示数据,但它让我一直抛出错误,我只是尝试再次运行ionic serve,但没有任何效果

我尝试制作 {{tarefa[0].numero}} 但这样他甚至没有向我显示模板中的数据。

【问题讨论】:

标签: javascript json angular typescript ionic-framework


【解决方案1】:

像下面这样捕获json的索引怎么样-

this.tarefa = data[0] 
console.log(this.tarefa)//Here I can show the data

然后{{tarefa.numero}} 应该适合你。

【讨论】:

  • 现在数据正在渲染,但一直在抛出错误,如您所见...我编辑了问题
【解决方案2】:

正如其他人所说,this.tarefa 是一个数组,包含您想要的所有数据的对象位于数组的第一个元素中。

通过以下方式访问它

this.tarefa[0].numero

或者当您检索数据并将其存储在 tarefa 变量中时,只需存储数组的第一个(也是唯一一个)元素。

this.tarefa = data[0]

【讨论】:

  • 第二个建议对我有用,现在模板没问题,但是控制台一直给我报错,我不知道为什么:/
  • 您必须在对 API 的 get 请求实际完成之前调用 tarefa.numero。
  • 所以,我必须做异步和等待??我知道它是做什么的,但我不知道如何实现,你能帮我吗?
  • 抱歉,我不太了解 Angular。你不需要使用异步等待,但你需要告诉 Angular 在实际获取数据之前不要加载模板。
猜你喜欢
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2022-11-15
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多