我正在使用维基百科的 api,响应如下所示:
{
'query': {
'pages': {
212187: {
'extract': value;
}
}
}
}
我正在尝试获取提取值。但是,当我无法通过 212187 时,因为它是一个会随着我调用的每个电话而改变的号码。这不允许我准确地模拟出响应对象。 我拥有的当前模型在 212187 级别未定义并阻止我进行提取。
我怎样才能做到这一点?任何帮助/建议/提示将不胜感激。
更新 我有一个与响应结构完全匹配的接口(interface),除了我拥有的 212187 作为数字(假设这是错误的)。 我的请求看起来像:
fetchDescriptionWiki(qSearch: string) {
const params: URLSearchParams = new URLSearchParams();
params.set('origin', '*');
params.set('format', 'json');
params.set('action', 'query');
params.set('prop', 'extracts');
params.set('exintro', '');
params.set('explaintext', '');
params.set('indexpageids', '');
params.set('titles', qSearch);
const options = new RequestOptions({
search: params
});
return this.http.get(this.pendingCardsDescriptionWikiUrl, options)
.map(this.extractApiData);
}
提取ApiData:
private extractApiData(res: Response) {
const body = res.json();
return body || [];
}
我的 component.ts 函数如下所示:
getDescription() {
this.pendingCardService.fetchDescriptionWiki('SomeStringValue')
.subscribe(data => {
this.wikiResult = data;
});
}
这就是我无法深入研究响应并获取提取值的原因。
最佳答案
我使用了以下内容来使用 Angular HttpClient (Angular 4+) 从维基百科 API 提取查询中检索数据。它利用 Object.keys()然后通过数组索引(在本例中为索引 0)定位所需的页面,这样您就不需要知道页面 ID。
我已经更新了答案以使用您示例中的类和方法名称。我建议升级到 HttpClient
,但您可以使用 Angular 2 的 Http
获得相同的结果。
@Injectable()
export class PendingCardService {
private: string wikipediaUrl =
'https://en.wikipedia.org/w/api.php?action=query' +
'&format=json&prop=extracts&exintro=1&explaintext=1' +
'&origin=*&titles=Some_title';
fetchDescriptionWiki(): Observable<any> {
// this can use URLSearchParams as you did
return this.http.get(this.wikipediaUrl).map(this.extractApiData);
}
private extractApiData(res: Response): Foobar {
// json() is unnecessary in Angular 4+ as json() is automatically called
const body = res.json();
const pages = body.query.pages;
const pageKeys = Object.keys(pages);
// Retrieve the first page (index 0)
const page = pages[pageKeys[0]];
// ES6 object destructuring to get extract value
const { extract } = page;
// creating some object from retrieved value
const foobar: Foobar = { extract };
return foobar;
}
}
组件:
getDescription() {
this.pendingCardService.fetchDescriptionWiki()
.subscribe((foobar: Foobar) => {
this.wikiResult = foobar;
});
}
希望对您有所帮助!
关于javascript - 使用未知数的键处理对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723177/