我正在尝试通过外部 api 从 json 数据获取键值对,并使用 Angular 和 TypeScript 显示它。我怎样才能实现这个目标?

2024-04-10

我想从我的 api 获取结果对象中的每个键值对以显示在我的前端上。即(类别、类型、难度、问题正确答案)我已正确设置服务和组件,我需要做的就是获取 json 并显示每一对。该方法名称称为 fetchQuestions,如下所示。我只需简单地以与 fetchPeople 相同的方式调用它就可以成功获取数据,但 json 格式不一样,所以它没有显示。然后我尝试了其他方法,但这也不起作用。我怎样才能实现这个显示?

人民服务

 import { Injectable } from '@angular/core';
 import { Observable } from  'rxjs/Observable';
 import { HttpClient } from '@angular/common/http';
 import { map } from 'rxjs/operators';

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

 constructor(private http: HttpClient) { }


//this works like a charm as it is just a simple array

fetchPeople(): Observable <Object> {
return this.http.get('/assets/data/people.json')
}




// this doesn't work as the json from the api below is in a different 
  // json format. Plus I need to return all value pairs

fetchQuestions(): Observable <Object> {
return this.http.get('https://opentdb.com/api.php? 
 amount=10&difficulty=hard&type=boolean').map(res => 
res.json().results).subscribe(data => {
console.log(data););
    }
  }

API

   {
   "response_code": 0,
   "results": [
   {
   "category": "Vehicles",
   "type": "boolean",
   "difficulty": "hard",
   "question": "In 1993 Swedish car manufacturer Saab experimented 
   with replacing the steering wheel with a joystick in a Saab 9000.",
   "correct_answer": "True",
   "incorrect_answers": [
    "False"
   ]
   },
   {
  "category": "History",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Japan was part of the Allied Powers during World War 
  I.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
  },
  {
  "category": "History",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The Kingdom of Prussia briefly held land in Estonia.",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
  },
  {
  "category": "Science: Mathematics",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The binary number &quot;101001101&quot; is equivalent 
  to the Decimal number &quot;334&quot;",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
  },
  {
  "category": "Entertainment: Video Games",
  "type": "boolean",
  "difficulty": "hard",
  "question": "TF2: Sentry rocket damage falloff is calculated based 
 on the distance between the sentry and the enemy, not the engineer 
  and the enemy",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
 },
  {
  "category": "Entertainment: Video Games",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The names of Roxas&#039;s Keyblades in Kingdom Hearts 
  are &quot;Oathkeeper&quot; and &quot;Oblivion&quot;.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Entertainment: Music",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The band STRFKR was also briefly known as Pyramiddd.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Entertainment: Books",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Harry Potter was born on July 31st, 1980.",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
  ]
},
{
  "category": "Entertainment: Japanese Anime & Manga",
  "type": "boolean",
  "difficulty": "hard",
  "question": "Druid is a mage class in &quot;Log Horizon&quot;.",
  "correct_answer": "False",
  "incorrect_answers": [
    "True"
  ]
},
{
  "category": "Geography",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The two largest ethnic groups of Belgium are Flemish and Walloon. ",
  "correct_answer": "True",
  "incorrect_answers": [
    "False"
     ]
   }
 ]
}

People.page.ts

 import { Component, OnInit } from '@angular/core';
 import { PeopleService } from './../../providers/people.service'
 @Component({
 selector: 'app-people',
 templateUrl: './people.page.html',
 styleUrls: ['./people.page.scss'],
 })
 export class PeoplePage implements OnInit {

 people$;
 results$;
 constructor(private peopleService:PeopleService) { }

 fetchPeople(){
 this.people$ = this.peopleService.fetchPeople();
 }
 fetchQuestions(){
  this.results$ = this.peopleService.fetchQuestions()
 }




  ngOnInit() {
  }

 }

People.page.html

   <ion-toolbar>
   <ion-title>people</ion-title>
   </ion-toolbar>
   </ion-header>
   <ion-button (click) ="fetchPeople()"  color="primary">Primary</ion- 
   button>

   <ion-list>
   <ion-item *ngFor="let person of people$ | async">{{person.name}}. 
   </ion-item>
   </ion-list>
   <ion-button (click) ="fetchQuestions()"  
   color="primary">Secondary</ion-button>
   <ion-list>
            <ion-item *ngFor="let result of results$ | async">. 
             {{result.category}}</ion-item>
             <ion-item *ngFor="let result of results$ | async"> 
            {{result.questions}}</ion-item>
           <ion-item *ngFor="let result of results$ | async"> 
           {{result.difficulty}}</ion-item>
           <ion-item *ngFor="let result of results$ | async"> 
            {{result.correct_answer}}</ion-item>
   </ion-list>
  <ion-content>
 <ion-button color="primary">Primary</ion-button>
 </ion-content>

HTTP GET 是冷可观察的。就这样每个async将触发单个请求。此外,您实际上并没有从fetchQuestions()功能。应删除订阅。

你也可以使用角度HttpParams https://angular.io/api/common/http/HttpParams设置查询参数并以 Angular 方式执行操作。

尝试以下操作

Service

import { HttpClient, HttpParams } from '@angular/common/http';

fetchQuestions(): Observable<any> {
  const params = new HttpParams()
    .set('amount', '10')
    .set('difficulty', 'hard')
    .set('type', 'boolean');  
  return this.http.get('https://opentdb.com/api.php', { params: params })
    .pipe(map(res => res.results));
}

Template

<ng-container *ngFor="let result of results$ | async">
  <ion-list>
    <ion-item>{{result.category}}</ion-item>
    <ion-item>{{result.question}}</ion-item>
    <ion-item>{{result.difficulty}}</ion-item>
    <ion-item>{{result.correct_answer}}</ion-item>
  </ion-list>
</ng-container>

我还注意到一个小类型。result.questions实际上应该是result.question.

有关热观察值与冷观察值的更多详细信息:https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html

工作示例:斯塔克闪电战 https://stackblitz.com/edit/angular-kkzftr

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我正在尝试通过外部 api 从 json 数据获取键值对,并使用 Angular 和 TypeScript 显示它。我怎样才能实现这个目标? 的相关文章

随机推荐

  • 如何将系统变量值传递给执行 SQL 任务中的 SQL 语句?

    SSIS 2008 非常简单的任务 我想检索系统变量并在 SQL INSERT 中使用它 我想检索的值System MachineName并在插入语句中使用它 使用声明INSERT INTO MYLOG COL1 SELECT System
  • C++ - 在文本文件中查找和替换(标准系统库)

    我正在寻找一些建议 我的情况 应用程序适用于文本本地文件 文件中的某处有这样的标签 correct TEXT 不幸的是 之间可以有无限的空格correct and TEXT 获得的文本正在功能测试中 可能会被替换 更改必须存储在文件中 co
  • 更改列表视图中文本视图的可见性

    我有一个列表视图 它由来自单独布局文件的两个文本视图组成 我用一个BaseAdapter从 JSON 文件构建列表 我希望第一个文本视图 标题 可单击 如果单击它会显示第二个文本视图 文本 如果再次单击它会隐藏它 当我使用onClick a
  • kibana server.basePath 结果为 404

    我在 RHEL 7 2 上运行 kibana 4 4 1 当 kibana yml 文件不包含设置时一切正常server basePath Kibana 成功启动并吐出消息 info listening Server running at
  • 在哪里可以找到 PHP 的错误日志文件?

    在哪里可以找到错误日志文件 我需要检查它们以解决安装后显示的内部服务器错误suPHP https wiki archlinux org title SuPHP 您可以使用lsof https en wikipedia org wiki Ls
  • Asterisk AGI:如何获取或设置全局变量的值?

    我使用 Asterisk 1 8 和 PHP 来编写 AGI 脚本 EDIT 我正在努力从 AGI PHP 脚本中设置和获取全局变量的值 我可以设置通道变量 但不能设置全局变量 使用 PHPAGI 库 Tried Set varname v
  • Puppeteer 在非无头模式下打开一个空选项卡

    运行 puppeteer npm 的最新版本 0 13 0 并将参数传递给 puppeteer launch headless false chrome 以空页面作为第一个选项卡打开 并从第二个选项卡中的脚本打开实际页面 const pag
  • 尝试调整 2fs EB 卷大小失败 [已关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我有一个 200GB 的 EBS 卷 正在尝试增加可用空间 我按照以下说明进行操作 http www hellersoftware com
  • Swift:通过 Twitter 分享文本

    所以基本上我正在制作一个事件应用程序 一切都很顺利 只是将活动分享到了 Twitter 我已经在互联网上搜索过 但我得到的只是使用我不想要的 Twitter 的本机应用程序 我想使用浏览器发推文 我已经实现了这个方法用于FB共享 任何想法都
  • terraform 资源创建 - this 关键字

    我在几个例子中发现了一种模式terraform代码在Github resource aws vpc this 我想知道关键字如何this与命名资源相比 提供了特殊的优势 我找不到哈希公司文档关于this关键词 https github co
  • 正则表达式:仅匹配一次

    我有一个包含多个 IP 地址和一些随机内容的字符串 例如像这样的 21 Jun 2018 01 15 38 0000 188 79 169 152 157 52 69 50 443 GET 157 52 69 30 157 52 69 10
  • C++:删除打印机队列

    我正在尝试从打印机中删除队列中的所有文件 我发现这看起来很简单 我尝试使用下面的代码删除队列 它可以编译 但 SetPrinter 返回 false 我收到的错误消息是 5 我尝试使用该方法将其解码为 正常 错误消息从这个问题 https
  • 是什么导致 Safari 中的音频播放缓慢/延迟?

    var audio new Audio data audio wav base64 UklGRoABAABXQVZFZm10IBAAAAABAAEAiBUAAIgVAAABAAgAZGF0YVwBAACHlqa1xNLg7vv Tk1LSk
  • 按 iframe 内的 Youtube 订阅表单按钮

    我正在搜索如何从 Youtube 订阅表单按下订阅按钮 但我没有找到任何可以帮助我的东西 我是 JS 新手 所以我希望你能帮助我 用于按下订阅按钮here http www youtube com subscribe widget p aa
  • 如何在 JavaScript 中模拟 target="_blank"

    当用户单击链接时 我需要更新数据库中的字段 然后在新窗口中打开请求的链接 更新没问题 但我不知道如何打开新窗口而不要求他们单击另一个超链接 a href http www mydomain com ReportID 1 target bla
  • 如何在 ASP.NET MVC 3 Intranet 应用程序中重新验证用户身份?

    该应用程序已经使用 Windows 集成安全性 而不是 Forms 我想要完成的是所谓的 逐步 身份验证 或针对以下情况的 强制重新身份验证 用户正在浏览网站做一些常见的 琐碎的事情 突然 用户必须执行敏感操作 例如授权 资源分配或确认汽车
  • iPhone开发与越狱

    我是 iPhone 开发新手 我们可以通过以下方式开发iphone应用程序 legal 越狱 如果我越狱了我的iPhone操作系统 之后我可以安装最新版本的iPhone操作系统吗 并从苹果网站再次使其合法 如果我开发越狱应用程序 我可以将其
  • .NET MVC:调用 RedirectToAction 传递模型?

    我有一个观点List aspx与班级绑定的Kindergarten 在控制器中 public ActionResult List int Id Kindergarten k from k1 in kindergartensRepositor
  • Android - 包括 GitHub 库 ActionBar PullToRefresh

    我在包含来自 GitHub 的库时遇到问题 这是图书馆 https github com chrisbanes ActionBar PullToRefresh https github com chrisbanes ActionBar Pu
  • 我正在尝试通过外部 api 从 json 数据获取键值对,并使用 Angular 和 TypeScript 显示它。我怎样才能实现这个目标?

    我想从我的 api 获取结果对象中的每个键值对以显示在我的前端上 即 类别 类型 难度 问题正确答案 我已正确设置服务和组件 我需要做的就是获取 json 并显示每一对 该方法名称称为 fetchQuestions 如下所示 我只需简单地以