angular - 组件生命周期
问题描述
还有一个问题,我不知道该怎么办。我认为问题出在组件的生命周期上,但不知道如何解决它。
文章列表.components.ts
export class ArticlesListComponent implements OnInit {
constructor(private articleService: ArticleService) {
}
@Input() articlesList;
articleInfo: IArticleInfoArray;
articlesTitles: string[];
allArticlesInfo: any[] = [];
averageLength: number;
static getUrlInfo(searchQuery: string) {
return 'https://ru.wikipedia.org/w/api.php?action=query&titles='
+ searchQuery + '&prop=info&format=json&origin=*';
}
ngOnInit() {
}
getArticlesTitle() {
this.articlesTitles = this.articlesList[1];
}
getArticlesInfo() {
for (const title of this.articlesTitles) {
this.articleService.getArticlesInfo(ArticlesListComponent.getUrlInfo(title))
.subscribe(
(data: IArticleInfo) => {
this.articleInfo = {
...data,
query: {
pages: [Object.values(data.query.pages)[0]]
}
};
this.allArticlesInfo.push([this.articleInfo.query.pages[0].touched, this.articleInfo.query.pages[0].length]);
}
);
}
}
getAverageLength() {
let sum = 0;
for (const length of this.allArticlesInfo) {
sum += length[1];
}
this.averageLength = sum / this.allArticlesInfo.length;
}
}
文章-list.component.html
<div class="articles-list pt-2" *ngIf="articlesList">
<div class="ml-2">
<h4>По запросу <small class="text-muted query">"{{ articlesList[0] }}"</small>
найдены статьи:</h4>
<h6>Количество найденных статей: {{ articlesList[1].length }}</h6>
</div>
<div class="articles-list__block" *ngFor="let article of articlesList[1]; let i = index">
<div *ngFor="let link of articlesList[3]; let k = index" [hidden]="i != k">
<a class="articles-list__link" [attr.href]="link">{{ article }}</a>
</div>
<div class="articles-list__description mt-2 mb-2" *ngFor="let description of articlesList[2]; let j = index" [hidden]="i != j">
<div *ngIf="description !== ''; else missingSnippet">{{ description }}</div>
<ng-template #missingSnippet>Краткое описание отсутствует</ng-template>
</div>
</div>
</div>
<div *ngIf="articlesList">
<button type="button" class="btn btn-info btn-sm"
(click)="getArticlesTitle(); getArticlesInfo(); getAverageLength()">Дополнительная информация</button>
<ng-container *ngIf="averageLength">
{{ averageLength }}
</ng-container>
</div>
问题是该值averageLength
仅在按下第二个按钮后出现。
我尝试getArticlesTitle(); getArticlesInfo();
在方法中使用函数ngOnInit
,但是会出现错误Cannot read property '1' of undefined
我该怎么办?组件初始化后如何立即获取值averageLength
?
解决方案
因此,在 ngOnInit() 中调用这些函数。
export class ArticlesListComponent implements OnInit {
constructor(private articleService: ArticleService) {
}
@Input() articlesList;
articleInfo: IArticleInfoArray;
articlesTitles: string[];
allArticlesInfo: any[] = [];
averageLength = 0;
static getUrlInfo(searchQuery: string) {
return 'https://ru.wikipedia.org/w/api.php?action=query&titles='
+ searchQuery + '&prop=info&format=json&origin=*';
}
ngOnInit() {
this.getArticlesTitle();
this.getArticlesInfo();
}
getArticlesTitle() {
this.articlesTitles = this.articlesList[1];
}
getArticlesInfo() {
for (const title of this.articlesTitles) {
this.articleService.getArticlesInfo(ArticlesListComponent.getUrlInfo(title))
.subscribe(
(data: IArticleInfo) => {
this.articleInfo = {
...data,
query: {
pages: [Object.values(data.query.pages)[0]]
}
};
this.allArticlesInfo.push([this.articleInfo.query.pages[0].touched, this.articleInfo.query.pages[0].length]);debugger;
this.calculateAvaerage();
}
);
}
}
calculateAvaerage(){
let sum = 0;
for (const length of this.allArticlesInfo) {
debugger;
sum += length[1];
}
this.averageLength = sum / this.allArticlesInfo.length;
}
}
但是在getArticlesTitle()
您尝试访问的内部方法中this.articlesList[1]
。这个会抛出一个错误,因为 this.articlesList 在 undefined 因为数据还没有填充。
要解决此问题,您需要稍微更新搜索组件。
添加*NgIf
搜索组件html的html,并将articles初始化为一个空数组,这样我们就可以使用length属性来判断是否加载该app-article-list
组件。
所以,用 -更新search.component.ts
articles: any[] = [];
和search.component.html与 -
<app-articles-list *ngIf="articles.length > 0" [articlesList]="articles">
</app-articles-list>
因此,app-article-list
当文章中有一些项目时,组件将加载。
这是更新的堆栈闪电战
推荐阅读
- java - Java 14 Record 文档中“浅不可变”的含义
- maven - 我们可以在同一个 pom.xml 文件中执行多个配置文件吗
- python - 如何创建仅包含一个版本的 python/pip 的 python 虚拟环境?
- python - 404 Flask 部署在 2008R2 - iis7
- python - 即使安装了 slack 和 slackclient 模块,也无法从 slack 导入 WebClient?
- javascript - 动画/滑动侧菜单不向左滑动?
- java - 当 Y 值大于 X 值时,二维数组的用户输入
- alexa - 部署到 lambda 时询问部署挂起
- lotus - Lotus Notes - CreateMIMEEntity 未释放对 .NSF 文件的控制
- javascript - 调用 servlet 后保持 Collapse 状态