我正在使用 Angular 2 和 Electron 制作一个应用程序,并使用 NeDB 作为数据存储。
搜索服务旨在处理与 DB 的操作,现在我希望它加载整个数据库并返回它。
搜索服务.ts
import { Injectable } from '@angular/core';
import * as Datastore from 'nedb';
import * as path from 'path';
@Injectable()
export class SearchService {
constructor() { }
getData(){
var db = new Datastore( {
filename: path.resolve('src/assets/db.json'),
autoload: true,
});
var result;
db.find({}, function(err, docs) {
result = docs;
});
console.log(result);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的组件中,我使用一种方法在使用 ngOnInit 钩子初始化组件时调用服务的 getData() 方法。
但是当我记录结果时,我得到undefined.
在修补搜索服务时,我发现docs我的find()方法无法从方法外部访问,而且似乎result = …
因此,我有一个过滤管道并使用它来过滤城市列表以仅显示那些包含搜索词的城市。
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform{
transform(value: any, arg: string) {
var searchTerm = arg ? arg : '';
searchTerm = searchTerm.toUpperCase();
if (value == null) return null;
return value.filter(el => el.City.toUpperCase().indexOf(searchTerm) !== -1);
}
}
Run Code Online (Sandbox Code Playgroud)
但是我拥有的城市数组中有 5000 个项目,所以我使用切片管只显示其中的五个。
<form [formGroup]="form">
<input formControlName="search" type="text">
<div>
<li
*ngFor="let city of cities | filter:searchTerm | slice:0:5"
(click)="PasteCity(city.City)">
{{ city.City }}
</li>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
但是有一个问题。我需要向用户显示找到了多少个城市,例如“显示了 5 0f 631 个城市”。据我尝试,ViewChildren索引*ngFor方法的最后一个元素只会让我得到显示的城市数量,而不是过滤器找到的......但是在尝试使用时ViewChildren …