2017-08-03 114 views
0

文件結構後PARAMS,並使http請求,我得到的結果,如果我再次搜索我無法得到結果。搜索一次,不能再次搜索

faq.component.ts

onRecievingResults() { 
    this.router.navigate(['results', this.inputValue], {relativeTo: this.route}); 
} 

搜索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

的組件將初始化一次這一切關於搜索欄。 – Hoyen

+0

在你的formcontrol上綁定'valueChanges' –

+0

如何重複它一遍又一遍,以便我可以搜索不同的值? @Hoyen –

回答

0

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; 
} 

根據你的要求有關服務參考檢查這個plunker

+0

謝謝!看起來很好,我試試這個。 –

+0

我如何做到這一點,如果我有父組件中的輸入框是** faq.component.html **和子組件的結果頁** search-results.component.html ** –

+0

更新@Samson – k11k2

0

您應該訂閱輸入的變化:

@Output() searchEvent: EventEmitter = new EventEmitter(); 

this.searchBox 
    .valueChanges 
    .debounceTime(200) 
    .subscribe((event) => this.searchEvent.emit(event)); 
+0

在哪個組件中我應該添加這個 –

+0

'@ output'用於將數據從子組件發送到父組件,並且它應該用在子組件中。 – k11k2

+0

我只是想再次搜索@ k11k2 –