简体   繁体   English

按关键字过滤数组在Angular中不起作用

[英]Filter array by keyword is not working in Angular

I created an angular "filter component" to filter an array and print out its contents. 我创建了一个有角度的“过滤器组件”以过滤数组并打印出其内容。 I'm getting the keyword as value for filter array from another component by a service. 我正在通过服务从另一个组件获取关键字作为过滤器数组的value In the html, value and the whole array is showing, but the filter array is not showing. 在html中,显示了value和整个数组,但未显示filter数组。

Below is my code: 下面是我的代码:

result.component.ts result.component.ts

import { Component, OnInit} from '@angular/core';
import { SendDataService } from "./../send-data.service";
import { HttpClient} from '@angular/common/http';
import { JsoncallItem } from "./../jsoncall-item";

@Component({
  selector: 'app-search-result',
  templateUrl: './search-result.component.html',
  styleUrls: ['./search-result.component.css']
})
export class SearchResultComponent implements OnInit {

    _postsArray: JsoncallItem[] = [];

    private postsURL ="http://myapp/browse/all/all";

  constructor(private http: HttpClient, private data: SendDataService){}

  getPosts(): void{
  this.http.get<JsoncallItem[]>(this.postsURL).
  subscribe(
      resultArray => {this._postsArray = resultArray['data'];
   })
  }

  value: string;

  filterarray: any[];

  showData(){
    this.filterarray=this._postsArray.filter(
        f => f.title.toLowerCase().includes(
          this.value.toLowerCase()))
    .map(searchname=>searchname.title)
  }

    ngOnInit(): void{
    this.getPosts();
    this.showData();
    this.data.currentValue.subscribe(value => this.value = value)

  }

}

result.component.html result.component.html

<p>{{value}}</p>
<table">
    <tr *ngFor="let item of filterarray">
        <td>{{item}}</td>
    </tr>
</table>

Only {{value}} is showing and {{item}} is not. 仅显示{{value}}没有显示{{item}} How I can solve this? 我该如何解决?

You are calling this.getPosts and this.showData both one after another on ngOnInit() 您正在ngOnInit()上依次调用this.getPosts和this.showData

this.getPosts is an asynchronous call, hence your this.showData is being run before the results from this.getPosts is fetched. this.getPosts是一个异步调用,因此您的this.showData在获取this.getPosts的结果之前正在运行。 Hence there is nothing to filter :) 因此,没有什么可以过滤的:)

The solution to this is to put this.showData within the success callback of this.getPosts. 解决方案是将this.showData放入this.getPosts的成功回调中。 Hence showData will only be called when the get method has completed successfully and there is some data to filter :) 因此,仅在get方法成功完成并且有一些数据需要过滤时才调用showData:

Something like this. 这样的事情。

getPosts(): void{
  this.http.get<JsoncallItem[]>(this.postsURL).
  subscribe(
      resultArray => {this._postsArray = resultArray['data'];
      this.showData();
   })
  }

And remove this.showData from ngOnInit() 并从ngOnInit()中删除this.showData

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM