该实例以 MongoDB + Node.js 的 Restful API Service为后台。 目前仅仅放一些代码片段,后期会将整个Demo Code上传到GitHub,待上传之后,会在本文中更新链接。
1. 后台实现:
'use strict';
var mongoose = require('mongoose'),
Community = mongoose.model('community');
var communityCtrl = require('../controllers/communityController');
exports.find_communities = function (req, res) {
Community.find({ name: communityCtrl.fuzzyMatch(req.query.name) }, function (err, task) {
if (err)
res.send(err);
res.json(task);
});
};
//使用正则表达式模糊匹配
exports.fuzzyMatch = function(source) {
let regexSearchString = '\.*' + source + '\.*';
return new RegExp(regexSearchString, 'i');
}
2.前端
2.1 RestSerice.ts 中调用后台
import { HttpClient, HttpParams } from '@angular/common/http';
import { AppSettings } from '../../settings/app-settings';
import { Injectable } from '@angular/core';
@Injectable()
export class AutoCompleteServiceProvider {
apiUrl: string;
constructor(public http: HttpClient) {
this.apiUrl = AppSettings.getAPIServiceURL();
}
getResults(keyword) {
const params = new HttpParams().append("name", keyword);
return new Promise(resolve => {
this.http.get(this.apiUrl + '/findcommunity', { params: params }).subscribe(data => {
resolve(data);
}, err => {
console.log('findcommunity' + err.message);
});
});
}
}
2.2 前端页面
community-select.html 代码中,使用 ion-searchbar 组件
< ion-searchbar (ionInput)="searchTextChange($event)" [placeholder]="promptmsg"
name="searchQuery" [(ngModel)]="searchQuery" #fieldsearch="ngModel" required >
community-select.ts 代码片段。
hideList: boolean;
coms: any;
scrollClass: string;
searchTextChange(ev: any) {
if (ev.target.value.length > 1) {
this.scrollClass = "scroll-max scroll-y";
this.hideList = false;
this.autoService.getResults(ev.target.value).then(x => {
this.coms = x;
this.coms.forEach(element => {
JSON.stringify(element);
});
});
} else {
this.scrollClass = "scroll-min";
}
}