有这样的问题,我一直在折磨的几天,我还是相当新手。
使用GET请求,维基百科的API,我得到这个对象
事实证明,对于网页对象,属性的名称(这也是一个对象)总是等于的pageid(在这种情况下,“9475”)。 我如何才能访问这个对象,如果我事先不知道什么名字将有多少?
然后该对象必须被转换成阵列,使得可以使用ngFor。
这个对象我开始使用showArticleInformation方法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),
);
}
}