Search code examples
angularangular2-routingangular2-templateangular2-formsangular2-services

Http request doesnot take the inputvalue again for the second time


I have a inputbox that i have written in the html and i am getting whatever I type in inputbox via two way databinding in .ts file.InputBox is in the parent component

<input [(ngModel)]="inputValue" placeholder="Search FAQ" type="text"/>
<button type="submit" (click)="onRecievingResults()"></button>

This is the .ts file here i get the input text and i pass the value to child component using params field.

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

Here i get the input value using subscribe and i pass http request service and i get the results first time.But when i pass the value again it doesn't take the value and give the results.

ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.inputValue = params['inputValue'];
}
);

this.faqService.getServers(this.inputValue)
    .subscribe(
    (data) => {
        this.item = data.items;
        console.log(this.item);
        },
        (error) => console.log(error)
    );
}

HTTP Request service

getServers(inputValue) {
    console.log(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);
        }
  );
}

Solution

  • its the right behavior according to your logic, let us follow the flow of events.

  • at first the component results is not exist
  • at the first click you are routing to result component
  • angluar instantiate the result component and execute ngOnInit method which execute your logic for the first time
  • you click the button for the second time.
  • angular will not re Instantiate result component because its already there, getServers(this.inputValue) will not be called.

    however the logic inside the params subscription is executed because the params value is changed, so you can solve it by moving getServers(this.inputValue) inside the params subscription callback. as follow:

    ngOnInit() {
        this.route.params.subscribe(  (params: Params) => {
           this.inputValue = params['inputValue'];
    
           this.faqService.getServers(this.inputValue).subscribe( 
             (data) => {
               this.item = data.items;
               console.log(this.item);
             },
             (error) => console.log(error)
           );
        });
    }