【问题标题】:Angular and JSON角度和 JSON
【发布时间】:2021-07-20 22:32:15
【问题描述】:

我正在实现一个简单的系统来在 Angular 中导入 JSON 元素。 一切正常:我使用了一个接口、一个可观察对象和一个指令。您可以在此处找到 JSON:http://jsonplaceholder.typicode.com/todos

现在,我想使用 JSON 文件中的布尔值“已完成”来在页面加载时显示或不显示用户。有一个布尔值“showUSer”和一个方法“displayUSer()”,但我不明白...... 我无法正确检索此 JSON 数据。 有什么想法吗? :>

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

interface JSP {
  "userId": string;
  "id": string;
  "title": string;
  "completed": boolean
}

@Component({
  selector: 'app-product',
  template: `<div class="display" *ngFor="let todo of todos">
              <div>User Id: {{todo.userId}}</div>
              <div >id: {{todo.id}}</div>
              <div *ngIf="showUser">Title: {{todo.title}}</div>
            </div>`,
  styles: ['.display {margin-top: 20px; margin-bottom: 20px;}']
  })

export class ProductComponent implements OnInit {
  title: string = "Products List";
  todos: JSP[];
  showUSer: boolean;

  constructor(private http: HttpClient){
  }

  ngOnInit(){
    this.http.get<JSP[]>('http://jsonplaceholder.typicode.com/todos')
    .subscribe(result => this.todos = result);
 }

 displayUSer(): void {
   this.showUSer = this.todos.completed;
 }

}

【问题讨论】:

    标签: json angular typescript


    【解决方案1】:

    Nitpicks:您的问题是 to display or not users,但您的代码似乎是 display or not the title。另外,为什么“USers”中的“S”要大写?

    问题是这个函数似乎忽略了你的实际数据布局:

     displayUSer(): void {
       this.showUSer = this.todos.completed;
     }
    

    todos 是控制器的属性。这是来自您进行的 api 调用的数组,它不包含 completed 属性,因此 this.todos.completed 将始终为 false。我有点惊讶您在编译打字稿时没有收到错误。

    看起来您希望此标志基于“待办事项”而不是页面范围,因此this.showUSer 没有意义。此外,无论如何您似乎都没有调用displayUSer 来设置值。

    既然您正在查看单个待办事项并且查询很简单,那么您为什么不直接查看标志?

    <div *ngIf="todo.completed">Title: {{todo.title}}</div>
    

    如果您想要根据某些条件设置页面范围的标志,您可以在订阅结果时执行此操作。在这里,我假设您将设置 showUSer 标志,如果 任何 待办事项被标记为已完成:

        this.http.get<JSP[]>('http://jsonplaceholder.typicode.com/todos')
        .subscribe(result => {
            this.todos = result;
            this.showUSers = result.reduce((previous, current) => previous || current.completed, false);
        });
    

    【讨论】:

    • 你是对的。我的方法名称不准确。我应该使用“showTitle”而不是“showUser”。谢谢你的帮助!你的回答超出了我的预期:)
    【解决方案2】:

    您的 JSON 没有任何 json.completed 值,而是 json[_].completed

    【讨论】:

    • 谢谢,我已经更改了 JSON 值并且可以正常工作。但我希望“完成”时显示“标题”为真,而“假”时不显示。
    • 更改模板&lt;div *ngIf="todo.completed"&gt;Title: {{todo.title}}&lt;/div&gt;
    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2021-07-18
    相关资源
    最近更新 更多