【问题标题】:Filtering data using angular使用角度过滤数据
【发布时间】:2022-11-27 04:19:02
【问题描述】:

我是 Angular 的新手,正在尝试过滤数据。我创建了一个显示酒店列表的网页,但想按星级过滤它们。我不知道如何尝试这个。任何帮助将不胜感激!

酒店.componenent.ts :

import { Component } from '@angular/core';
import { WebService } from './web.service';



@Component({
  selector: 'hotels',
  templateUrl: './hotels.component.html',
  styleUrls: ['./hotels.component.css']
})
export class HotelsComponent {

    hotel_list: any;
    page: number = 1;

    constructor(public webService: WebService) { }

    ngOnInit() {
        if (sessionStorage['page']) {
          this.page = Number(sessionStorage['page'])
        }
        this.hotel_list = this.webService.getHotels(this.page);
    }
       

网络服务.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';


@Injectable()
export class WebService {

    private hotelID: any;


    constructor(private http: HttpClient) { }

    getHotels(page: number) { 
        return this.http.get('http://localhost:5000/api/v1.0/hotels?pn=' + page);

    }

酒店.components.html:

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <div *ngFor = "let hotel of hotel_list | async">
                <div class="card text-white bg-primary mb-3" 
                     style ="cursor : pointer"
                     [routerLink]="['/hotels', hotel._id]">
                    <div class="card-header">
                        {{ hotel.hotel }}
                    </div>
                    <div class="card-body">
                        This hotel is based in
                        {{ hotel.city }}
                    </div>
                    <div class="card-footer">
                        {{ hotel.rating }}
                        stars
                    </div>
                </div>
            </div>

【问题讨论】:

  • 您期望应用的这些过滤条件是否需要发生在 UI 级别或 API 级别? API是否支持按评分查询酒店?

标签: html angular typescript filter


【解决方案1】:

假设您需要在获取酒店后在客户端过滤旅馆。也就是说,只有 page = 1 返回的酒店。

在 hotels.componenent.ts 中:

filtered_hotels_list: any = []; //empty array
//......
    ngOnInit() {
        if (sessionStorage['page']) {
          this.page = Number(sessionStorage['page'])
        }
        this.webService.getHotels(this.page).subscribe(data => { 
                this.hotel_list = data
                this.filter();
        });
        
}
filter(rating:number = -1) { // rating = -1 shows all
     if(rating > -1) {
         this.filtered_hotels_list = this.hotel_list.filter(o => o.rating == rating)
     } else this.filtered_hotels_list = this.hotel_list
 
}

在 hotels.components.html 中:

<div *ngFor = "let hotel of filtered_hotel_list">

并实现您的 UI 以添加一个过滤器按钮,该按钮调用 filter(5) 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    相关资源
    最近更新 更多