【问题标题】:Angular - Execute function after http requestAngular - http请求后执行功能
【发布时间】:2020-09-18 08:46:01
【问题描述】:

希望你没事。
我有一个博客组件,它通过 http 请求从数据库获取帖子。
所以,我正在尝试的是,当帖子在我的组件中时,我想用函数过滤它们。
我在订阅方法中获取帖子后调用此函数,但它不起作用。

过滤帖子的功能:

filtrarArticles(tipus)
  { 
    var articles = document.getElementsByClassName("article") as HTMLCollectionOf<HTMLElement>;

    for (var i = 0; i < articles.length; i++)
    {
      var tipusArticle = this.articles[i].categoria;
      

      if (tipus == tipusArticle) 
      {
          articles[i].style.display = "";
      } 
      else 
      {
          articles[i].style.display = "none";
      }
    }
  }

过滤我的函数的 HTML 代码:

<div class="articles row w-100 align-self-end d-flex justify-content-center">
      <div class="article col-xl-3 mb-md-0 mb-3" *ngFor="let article of articles; index as i" (click)="obrirModalArticle(article)">
        <img class="imatgeAllargada d-block w-100" src="https://drive.google.com/uc?id={{article.img}}">
        <br>
        <h4>{{article.title_article}}</h4>
        <p [innerHTML]="article.descripcio1"></p>
      </div>
</div>

articles 数组有一个属性,名称为“categoria”,它是过滤它的关键。

我在这里调用过滤函数:

this.articleService.obtenirArticles(this.idioma).subscribe(
      res=>
      {
        this.articles = res;

        this.filtrarArticles('generals');
      },
      error =>
      {
        alert("No s'han pogut obtenir els articles, intenta-ho més tard.");
      });
  
    this.translate.onLangChange.subscribe((event: LangChangeEvent) => 
    {
      this.idioma = event.lang;

      this.articleService.obtenirArticles(this.idioma).subscribe(
        res=>
        {
          this.articles = res;
        },
        error =>
        {
          alert("No s'han pogut obtenir els articles, intenta-ho més tard.");
        }
      )
    });


此代码在 init 方法上。而且我不知道为什么不起作用?

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    直接访问 DOM 被认为是一种不好的做法,原因之一是您不应该直接操作模板,而是让 Angular 为您完成。所以你应该做的是,创建一个模型并让 Angular 知道它,将它绑定到模板,一旦它发生变化,Angular 就会为你更新模板。

    组件

    export class YourComponent {
      allArticles;      // Property to hold the result of the response
      filteredArticles; // Property to hold what is going to be rendered on the template
    
      ...
    
      ngOnInit() {
        this.articleService.obtenirArticles(this.idioma).subscribe(res => {
          this.allArticles = res; // Save the original response
    
          this.filteredArticles = this.filtrarArticles('generals'); // Get the articles filtered and show this property on the template
        },
        error => {
          alert("No s'han pogut obtenir els articles, intenta-ho més tard.");
        });
    
        this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
          this.idioma = event.lang;
    
          this.articleService.obtenirArticles(this.idioma).subscribe(res => {
            this.allArticles = res; // Save the original response
            this.filteredArticles = [...this.allArticles]; // Clone the response array unfiltered
          },
          error => {
            alert("No s'han pogut obtenir els articles, intenta-ho més tard.");
          })
        });
      }
    }
    

    过滤功能

    filtrarArticles(tipus) {
      // The filter method will return a copy of the array once it has been iterated over each item.
      // If the condition is met, the item is going to be included in the resulting array, otherwise it won't.
      return this.allArticles.filter(article => article.categoria === tipus);
    }
    

    然后在您的模板中,您遍历 filterArticles 数组,一旦该数组更改,Angular 将更新模板。

    模板

    <div class="articles row w-100 align-self-end d-flex justify-content-center">
      <div class="article col-xl-3 mb-md-0 mb-3" *ngFor="let article of filteredArticles; index as i" (click)="obrirModalArticle(article)">
        <img class="imatgeAllargada d-block w-100" src="https://drive.google.com/uc?id={{article.img}}">
        <br>
        <h4>{{article.title_article}}</h4>
        <p [innerHTML]="article.descripcio1"></p>
      </div>
    

    【讨论】:

    • 您好@David Fontes,再次感谢您的回答,它有效。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多