【发布时间】:2019-02-03 07:11:47
【问题描述】:
出现这样的问题,苦了几天,还是个新手。
使用对 Wikipedia API 的 GET 请求,我得到 this object
事实证明,对于 pages 对象,属性的名称(也是一个对象)总是等于 pageid(在本例中为“9475”)。如果我事先不知道该对象的名称,如何访问该对象?
那么这个对象必须转换成数组才能使用ngFor。
我使用 search.component.ts
中的 showArticleInformation 方法获得的这个对象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),
);
}
}
【问题讨论】:
-
"那么这个对象必须转换成数组"。你能发布转换后的输出会是什么样子吗?像这样?:
{ batchComplete: string; query: { pages: [ {pageid, ns, length}] }; } -
@adiga 我想是的
{ batchComplete: string; query: { pages: [ pageid, ns, length] }通常,我只需要从整个对象中获取一个由 2 个值组成的数组:[length, touched]。
标签: javascript angular typescript wikipedia-api