我需要在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 { }发布于 2019-10-03 15:38:50
'? search =';在你的api中没有搜索参数,这就是你的代码不搜索的原因。
https://api.cdnjs.com/libraries尝试将您的api替换为此api,以测试它是否有效。
https://stackoverflow.com/questions/46717686
复制相似问题