组件的生命周期

问题描述 投票:1回答:1

还有一个问题,我不知道该怎么办。我认为这个问题是与组件的生命周期,但目前还没有想法如何解决它。

文章-list.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

angular typescript lifecycle
1个回答
2
投票

所以,调用弗莱功能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;
  }
}

但这里qazxsw POI方法里面你试图访问qazxsw POI。这一次将抛出,因为this.articlesList错误未定义的数据不填充呢。

为了解决这个问题,你需要更新搜索组件位。

添加getArticlesTitle()在搜索组件的HTML的HTML和初始化物品作为空数组,这样我们就可以使用length属性来确定我们是否加载this.articlesList[1]组件。

因此,具有更新search.component.ts -

*NgIf

与search.component.html -

app-article-list

所以,当文章中有一些项目articles: any[] = []; 组件将加载。

这里是更新<app-articles-list *ngIf="articles.length > 0" [articlesList]="articles"> </app-articles-list>

© www.soinside.com 2019 - 2024. All rights reserved.