问题
File Structure:

I have a input textbox , there i type something and pass that value to a function named onRecievingResults()
and pass that value to another component using params and make http
request and i get the results if i search again i am not able to get the results.
faq.component.ts
onRecievingResults() {
this.router.navigate(['results', this.inputValue], {relativeTo: this.route});
}
search-results.component.ts
export class SearchResultsComponent implements OnInit {
data: any[];
item: any[];
inputValue;
constructor(private faqService: FaqService,private route: ActivatedRoute,) {
}
ngOnInit() {
this.route.params.subscribe(
(params : Params) => {
this.inputValue = params["inputValue"];
}
);
this.faqService.getServers(this.inputValue)
.subscribe(
(data) => {
this.item = data.items;
},
(error) => console.log(error)
);
}
}
faq.service.ts
getServers(inputValue) {
return this.http.get(Staticdata.apiBaseUrl + "/2.2/search/advanced?key="+ Staticdata.key +"&access_token="+ Staticdata.access_token +"&/2.2/search/advanced?order=desc&sort=activity&accepted=True&closed=True&title=" + inputValue + Staticdata.redirectUrl + "&filter="+ Staticdata.filters)
.map(
(response: Response) => {
const items = response.json();
return items;
},
)
.catch(
(error: Response) => {
return Observable.throw(error);
}
);
}
回答1:
appcomponent.html
<app-child [items]="items"></app-child>
<form [formGroup]="searchForm"><input formControlName="search"></form>
appcomponent.ts
export class AppComponent implements OnInit {
searchForm: FormGroup;
search= new FormControl();
searchField: FormControl;
items;
constructor(private fb: FormBuilder, private service: AppService){}
ngOnInit(){
this.searchField = new FormControl();
this.searchForm = this.fb.group({search: this.searchField})
this.searchField.valueChanges
.debounceTime(400)
.switchMap(res => this.service.search(res))
.subscribe(res => {this.items = res});}
app-child.component.html
<h3>child component Search bar values of parent component</h3>
<div *ngFor="let item of items">
{{item}}
</div>
app-child.component.ts
@Component({
selector: 'app-child',
templateUrl: './appchild.component.html'
})
export class appChildComponent {
@Input()
items;
}
As you requested this all about search bar about service reference check this plunker
回答2:
You should subscribe to the changes in the input:
@Output() searchEvent: EventEmitter = new EventEmitter();
this.searchBox
.valueChanges
.debounceTime(200)
.subscribe((event) => this.searchEvent.emit(event));
来源:https://stackoverflow.com/questions/45486330/after-searching-once-not-able-to-search-again