【发布时间】:2019-02-03 10:49:35
【问题描述】:
有这样的问题。
我正在尝试使用循环在 Wikipedia API 中发出一定数量的 GET 请求。
尝试使用 getAllInfo() 函数来做到这一点
articles.components.ts
export class ArticlesComponent {
constructor(private articlesServices: ArticlesService) { }
@Input() allTitles: string[];
articlesInfo: ArticleInformationNew;
allArray: [[string, number]] = [['', 0]];
static getUrlInformation(searchQuery: string) {
return 'https://ru.wikipedia.org/w/api.php?action=query&titles='
+ searchQuery + '&prop=info&format=json&origin=*';
}
getAllInfo() {
for (const title of this.allTitles) {
this.articlesServices.getArticleInformation(ArticlesComponent.getUrlInformation(title))
.subscribe(
(data: ArticleInformation) => this.articlesInfo = {
...data,
query: { pages: [Object.values(data.query.pages)[0]]}}
);
this.allArray.push([this.articlesInfo.query.pages[0].touched, this.articlesInfo.query.pages[0].length]);
}
}
}
articles.service.ts
export interface ArticleInformation {
batchComplete: string;
query: {
pages: {
}
};
}
export interface ArticleInformationNew {
batchComplete: string;
query: {
pages: any[]
};
}
export class ArticlesService {
constructor(private http: HttpClient) { }
getArticleInformation(url) {
return this.http.get<ArticleInformation>(url);
}
}
数组this.allTitles 可以由多行组成。 例如:this.allTitles = ['Naumen', 'Naumen DMS']
我希望数组this.allArray 是二维的,并且包含由每个查询的数据行组成的数组。 例如:
this.allArray[0] = ['', 0]
this.allArray[1] = ['2019-02-01T23:27:26Z', 3687]
this.allArray[2] = ['2019-01-21T04:24:21Z', 9704]
但事实上,二维数组的每个元素都是一样的。 例如:
this.allArray[0] = ['', 0]
this.allArray[1] = ['2019-02-01T23:27:26Z', 3687]
this.allArray[2] = ['2019-02-01T23:27:26Z', 3687]
为什么以及如何解决它?
【问题讨论】:
-
HTTP 请求是异步的。您必须在订阅中更新数组。
-
@Arcteezy 嗨,又是我。你昨天帮了我很多:D你能告诉我具体写什么吗?
标签: arrays angular typescript get httprequest