【发布时间】:2018-03-24 20:50:06
【问题描述】:
我需要在 Angular 4 应用程序中创建搜索功能,数据已经是项目文件夹外部 url 中的 json 文档。 我需要能够访问按标题或作者搜索的数据,并获得搜索结果。 我在输入搜索框中输入时无法得到结果。
我现在的代码:
json数据*****
[
{
"title": "title1",
"author": "author1",
"users": [
{
"id": 1,
"name": "Isidro"
},
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 3,
"name": "Trinidad"
}
]
},
{
"title": "title2",
"author": "author2",
"users": [
{
"id": 4,
"name": "Jose Miguel"
},
{
"id": 5,
"name": "Beatriz"
},
{
"id": 6,
"name": "Rosario"
}
]
},
app.component.html******
<input
(keyup)="searchTerm$.next($event.target.value)">
<ul *ngIf="results">
<li *ngFor="let result of results">
<a href="{{ result.latest }}" target="_blank">
{{ result.title }}
</a>
</li>
</ul>
app.service.ts*********
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
@Injectable()
export class AppService {
baseUrl: string = 'https://raw.githubusercontent.com/elena-in-code/books/master/bookcollection.json';
queryUrl: string = '?search=';
constructor(private http:Http){}
search(terms: Observable<string>) {
return terms.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchEntries(term));
}
searchEntries(term) {
return this.http
.get(this.baseUrl + this.queryUrl + term)
.map(res => res.json());
}
}
app.component.ts*********
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';
import {Observable} from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService]
})
export class AppComponent {
results: Object;
searchTerm$ = new Subject<string>();
constructor(private appService: AppService){
this.appService.search(this.searchTerm$)
.subscribe(results => {
this.results = results.results;
});
}
}
app.module.ts*********
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
FormsModule
],
providers: [AppService],
bootstrap: [AppComponent]
})
export class AppModule { }
【问题讨论】:
-
为什么你的 baseUrl 在错误图像中有 .jsons 而在上面的代码中有 .json??
-
我修复了服务中的错误,但仍然没有设法获得搜索结果。所以没有错误了,在这里编辑代码。但不是功能。好眼力!谢谢。
-
如果它是一个真正的服务,它将在后端按照
search过滤数据并给你。由于它是一个json文件,您需要获取整个数据并在 UI 中过滤它们