我正在尝试创建一个过滤数据的Angular管道。用户输入搜索查询searchFilterFunction
,然后管道应仅从数组中筛选出具有匹配键值对municipality
的那些对象。
我试图创建一个municipality
到export
,但是那招没用。
app.module.ts
<div class="container">
<h1>Automatic Teller Machines</h1>
<div class="row form-group">
<div class="col">
<input class="form-control" type="text" [(ngModel)]="municipality" placeholder="Municipality">
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>Address</th>
<th>Location</th>
<th>Availability</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let atm of atms | search:municipality">
<td>{{ atm.target_address }}, {{ atm.postalnumber }}
{{ atm.municipality }}</td>
<td>{{ atm.location }}, {{ atm.location_type }}</td>
<td>{{ atm.availability }} {{ atm.availability_details }}</td>
</tr>
</tbody>
</table>
</div>
import { Component } from '@angular/core';
import { ATMsService } from '../app/atms.service';
interface atm {
target_address: string,
postalnumber: string,
municipality: string,
location: string,
location_type: string,
availability: string,
availability_details: string,
coordinates_lat: string,
coordinates_lon: string
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
municipality: string;
atms: atm[] = [];
constructor(public service: ATMsService) { }
searchByMunicipalityName = (municipality: string) => {
this.service.searchByMunicipalityName(municipality).then((data) => {
this.atms = data;
})
}
}
import { Pipe, PipeTransform } from '@angular/core';
interface atm {
target_address: string,
postalnumber: string,
municipality: string,
location: string,
location_type: string,
availability: string,
availability_details: string,
coordinates_lat: string,
coordinates_lon: string
}
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(atms: atm[], municipality: string): any {
let filteredAtms: atm[] = [];
if (municipality) {
filteredAtms= atms.filter(o => o.municipality== municipality.toUpperCase());
} else {
filteredAtms= atms;
}
return filteredAtms;
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { OttoautomaatitService } from '../app/ottoautomaatit.service';
import { SivutusPipe } from './sivutus.pipe';
import { HakuPipe } from './haku.pipe';
我希望能够从包含对象数组的JSON文件中过滤出数据,但是当我键入搜索查询 @NgModule({
declarations: [
AppComponent,
SearchPipe
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [ATMsService],
bootstrap: [AppComponent]
})
export class AppModule { }
时,什么也不会发生。在应该包含最终筛选数据的HTML表的位置,什么都不会出现。
答案 0 :(得分:0)
从您提供的代码中,我发现函数searchByMunicipalityName
应该填充atms
数组。但是它从未在任何地方被调用。我推测如果您将应用程序组件构造器更改为
constructor(public service: ATMsService) {
this.searchByMunicipalityName('');
}
可能会解决您的问题。