Home > Net >  How to make search functionality in angular
How to make search functionality in angular

Time:03-19

Please help me with this error I am getting this kind of object from the backend.

[
    {
        "_id": "623271addac895c8203c608d",
        "topic": "Liver",
        "subject": "Science",
        "userId": "6230ab6516f17ed82cbce749",
        "__v": 0
    },
    {
        "_id": "623482efa8575c84edcdb2ef",
        "topic": "Liver",
        "subject": "Science",
        "userId": "6230ab6516f17ed82cbce749",
        "__v": 0
    }
]

I have a search function which search the topic.

this is my HTML code

<input (keyup)="searchData($event)" type="text"  placeholder="Search" aria-label="Searchbox" aria-describedby="basic-addon1">
<span *ngFor="let topic of topics | keyvalue">{{topic}}</span>

This is my ts code

 topics: any 
  searchData(event: Event) {
    this.topics = (event.target as HTMLInputElement).value;
    console.log(this.topics)
    this.topicService.searchTopic(this.topics).subscribe(res => {
      console.log("Filter Response", res);
      this.topics = Array.from(Object.values(res))
    },
      (err) => {
        console.log(err);
        console.log("error")
      })
  }

this is my service code

 searchTopic(data: any): Observable<any> {
    return this.http.get(`${api_path}/search?topic=${data}`)
  }

On search, i am getting this response instead of getting topic name I am getting object object. i have two topic named liver so I am getting two object instead of getting the name of topic enter image description here

CodePudding user response:

Try to get field topic from the object

<span *ngFor="let item of topics | keyvalue">{{item.topic}}</span>

CodePudding user response:

I think you need to access them using the .key and .value when you use the keyvalue pipe.

<div *ngFor="let topic of topics | keyvalue">
      {{topic.key}}:{{topic.value.topic}}
</div>

Here is the Angular official site example

I also not sure why you use the pipe either. You can just the following to get the value.

<div *ngFor="let topic of topics">
  {{topic.topic}}
  {{topic.subject}}
</div>
  • Related