在 TypeScript 中将内部对象属性更改为数组 [英] Changing an inner object property to an array in TypeScript

查看:39
本文介绍了在 TypeScript 中将内部对象属性更改为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出现这样的问题,折腾了好几天了,我还是菜鸟.

使用对维基百科 API 的 GET 请求,我得到这个对象

事实证明,对于 pages 对象,属性的名称(也是一个对象)始终等于 pageid(在本例中为9475").如果我事先不知道它的名称,我如何才能访问它?

那么这个对象必须转成数组才能使用ngFor.

我使用 search.component.ts

中的 showArticleInformation 方法获得的这个对象

search.component.ts

import { Component, OnInit } from '@angular/core';从'../../services/articles.service'导入{文章,文章信息,文章服务};@成分({选择器:应用搜索",templateUrl: './search.component.html',styleUrls: ['./search.component.css'],提供者:[ArticlesService]})导出类 SearchComponent 实现 OnInit {构造函数(私人文章服务:文章服务){}搜索查询:字符串;文章:{};文章信息:文章信息;getUrl(搜索查询:字符串){返回'https://ru.wikipedia.org/w/api.php?action=opensearch&profile=strict&search='+ searchQuery + '&limit=100&namespace=0&format=json&origin=*';}getUrlInformation(搜索查询:字符串){返回 '​​https://ru.wikipedia.org/w/api.php?action=query&titles='+ searchQuery + '&prop=info&format=json&origin=*';}显示文章(){this.articlesServices.getArticles(this.getUrl(this.searchQuery)).订阅((数据:文章)=>this.articles = Object.values({ ...data }));}显示文章信息(){this.articlesServices.getArticleInformation(this.getUrlInformation(this.searchQuery)).订阅((数据:文章信息)=>this.articleInformation = { ...数据});console.log(this.articleInformation);}ngOnInit() {}}

articles.service.ts

import { Injectable } from '@angular/core';从'@angular/common/http' 导入 { HttpClient };从'rxjs/operators'导入{重试};导出接口文章{标题:字符串;集合:字符串[];描述:字符串[];链接:字符串[];}导出接口文章信息{批处理完成:字符串;询问: {页数:{}};}@Injectable({提供在:'根'})导出类文章服务{构造函数(私有http:HttpClient){}获取文章(网址){返回 this.http.get<文章>(url).管道(重试(3),);}获取文章信息(网址){返回 this.http.get(url).管道(重试(3),);}}

解决方案

如果您确定 pages 将始终具有一个属性,而您只需要它的 value,你可以使用 对象值:

const data = {批处理完成:"",询问: {页数:{9745":{pageid: 9745,长度:48,lastrevid: 100,内容模型:维基文本",感动:2019-02-01"}}}}const 文章信息 = {...数据,询问: {页:[Object.values(data.query.pages)[0]]}}console.log(文章信息)

但是,您需要为 this.articleInformationdata 设置一个单独的 interface,因为它们具有不同的结构.

像这样:

导出接口 ArticleInformationNew {批处理完成:字符串;询问: {页数:任何[]};}

There was such a problem, I have been suffering for a couple of days, I am still quite a novice.

Using the GET request to the Wikipedia API, I get this object

It turns out that for the pages object, the name of the property (which is also an object) is always equal to pageid (in this case "9475"). How can I get access to this object if I don’t know in advance what name it will have?

Then this object must be converted to an array so that ngFor can be used.

This object I get using the showArticleInformation method in search.component.ts

search.component.ts

import { Component, OnInit } from '@angular/core';
import { Article, ArticleInformation, ArticlesService } from '../../services/articles.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css'],
  providers: [ArticlesService]
})

export class SearchComponent implements OnInit {
  constructor(private articlesServices: ArticlesService) { }

  searchQuery: string;

  articles: { };
  articleInformation: ArticleInformation;

  getUrl(searchQuery: string) {
    return 'https://ru.wikipedia.org/w/api.php?action=opensearch&profile=strict&search='
      + searchQuery + '&limit=100&namespace=0&format=json&origin=*';
  }

  getUrlInformation(searchQuery: string) {
    return 'https://ru.wikipedia.org/w/api.php?action=query&titles='
      + searchQuery + '&prop=info&format=json&origin=*';
  }

  showArticles() {
    this.articlesServices.getArticles(this.getUrl(this.searchQuery))
      .subscribe(
        (data: Article) => this.articles = Object.values({ ...data })
      );
  }

  showArticleInformation() {
    this.articlesServices.getArticleInformation(this.getUrlInformation(this.searchQuery))
      .subscribe(
        (data: ArticleInformation) => this.articleInformation = { ...data }
      );
    console.log(this.articleInformation);
  }

  ngOnInit() {
  }
}

articles.service.ts

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

export interface Article {
  title: string;
  collection: string[];
  description: string[];
  links: string[];
}

export interface ArticleInformation {
  batchComplete: string;
  query: {
    pages: { }
  };
}

@Injectable({
  providedIn: 'root'
})

export class ArticlesService {
  constructor(private http: HttpClient) { }

  getArticles(url) {
    return this.http.get<Article>(url)
      .pipe(
        retry(3),
      );
  }

  getArticleInformation(url) {
    return this.http.get<ArticleInformation>(url)
      .pipe(
        retry(3),
      );
  }
}

解决方案

If you're certain that pages will always have one property and you need only it's value, you could do something like this using Object.values:

const data = {
  batchComplete: "",
  query: {
    pages: {
      "9745": {
        pageid: 9745,
        length: 48,
        lastrevid: 100,
        contentmodel: "wikitext",
        touched: "2019-02-01"
      }
    }
  }
}

const articleInformation = {
  ...data,
  query: {
    pages: [Object.values(data.query.pages)[0]]
  }
}

console.log(articleInformation)

But, you need to have a separate interface for this.articleInformation and data since they have different structures.

Something like this:

export interface ArticleInformationNew {
  batchComplete: string;
  query: {
    pages: any[]
  };
}

这篇关于在 TypeScript 中将内部对象属性更改为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆