Angular 2: Issue with Component not reinitializing when query parameters change

I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have noticed that when I change the search text, the data does not update but the query parameter changes.

navbar.component.ts

    @Component({
    selector:'navbar',
    template:`
    <div class="input-group">
       <input type="text" class="form-control" placeholder="Search" 
       name="srch-term" id="srch-term" [(ngModel)] = "search_text">
    <div class="input-group-btn">
       <button class="btn btn-default" (click)="search()">
         <i class="fa fa-search"></i>
       </button>
   </div>
     </div>`,
        styleUrls:['app/navbar/navbar.component.css'],
        directives:[LoginComponent,SignupComponent,ROUTER_DIRECTIVES]
        })
    export class NavbarComponent {
        State: NavbarState = "PUBLIC";

        profileNavElement: NavbarElement;
        userNameString: string;
        search_text : string = '';
    search(){
            console.log(this.search_text);
            if(this.search_text){
                this.router.navigate(["/search"],{
                    queryParams:{query:this.search_text}
                });
            }

        }

serach.component.ts

import { Component, OnInit, DoCheck } from '@angular/core';
import { ActivatedRoute,Router,ROUTER_DIRECTIVES}  from '@angular/router';
import { SearchService } from './search.service';
import {Location} from '@angular/common';

@Component({
    moduleId: module.id,
    selector: 'search',
    templateUrl: 'search.component.html',
    styleUrls:['./search.component.css'],
    providers:[ROUTER_DIRECTIVES,SearchService]
})
export class SearchComponent implements OnInit {

    query:string = '';
    videos:Object[] ;
    resultFound:boolean=false ;
    resultNotFound:boolean=false;

    constructor(private route:ActivatedRoute,
                private router:Router,
                private _searchService:SearchService) {

                }

    ngOnInit() {
        this.router.routerState
            .queryParams
            .subscribe(data => {
                this.query = data['query'];
        });
        this.getSearchResult();
    }


    getSearchResult(){
        this._searchService.getSearchResult(this.query)
            .subscribe((result) => {
                this.resultFound = true;
                this.resultNotFound = false;
                this.videos = result;
            },
            (error) => {
                this.resultFound = false;
                this.resultNotFound = true;
            });
    }

}

Any suggestions on how to address this issue? Your help is greatly appreciated. Thank you in advance.

Answer №1

It has been intentionally designed that way. When only the route parameters change, the component is reused.

To ensure that getSearchResult() is called every time the parameters change, you can simply move it inside the subscribe() method:

ngOnInit() {
    this.router.routerState
        .queryParams
        .subscribe(data => {
            this.query = data['query'];
            this.getSearchResult();
    });
}

While there are plans to support custom behavior in the future, it may not be implemented before the final version.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 - Issue with ngOnInit not being called upon routing to the same component multiple times

Currently, I am developing a web application using Angular 2. When there is data in my array, I navigate to the xyz component and store it in a service component. The ngOnInit() method of the xyz component retrieves data from the service and displays it ...

Tips for identifying when input fields have been altered within an AngularJS application

On my new page, users can input data without using a form. For example: <input type='text' ng-model='ExpReport.ReportName' /> <input type='text' ng-model='ExpReport.startdate' /> There is an exit button ...

Utilizing AngularJS and ADAL.JS to Define Resource ID (Audience)

Is there a way to utilize adal.js within AngularJS to obtain a bearer token for the audience https://management.azure.com through JavaScript? I have created a client application in Azure AD and configured its permissions to allow access to the "Windows Az ...

Angular2 tubes sieve through hyperlinks within HTML content

As I receive HTML strings from an external source, my goal is to filter out all links that contain images, remove the href attribute, and replace it with a click event. I have attempted to achieve this using an Angular pipe, but so far I have only been suc ...

IOS 10.3.3 dilemma: Screen flickering problem plaguing an ionic/cordova application

I'm currently developing a hybrid app using angular on ionic/cordova frameworks. The app works well on android devices, but when I run it on an iPad, there is some screen flickering happening. I've tried searching online for a solution or the cau ...

A perplexing issue arises in Angular 8 where a component placed between the header and footer fails to display, despite no errors being

I've encountered an issue with angular routing that I need assistance with. In the app.component.html file, we have: <router-outlet></router-outlet> The configuration in the app-routing.module.ts looks like this: import { NgModule } fr ...

How can I access a service without the need to import its provider module?

My goal is to grasp the concept of multiple NgModules in an angular application and how they interact, specifically focusing on importing a SharedModule for commonly used services into lazily loaded feature modules. Here's the sequence of steps I fol ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Trouble with the drop-down menu displaying "string:2" in an AngularJS application

Currently, I am utilizing AngularJS ng-model to choose the value from a drop-down menu. Additionally, I am implementing datatable for organizing the columns. <select id="{{user.id}}" ng-model="user.commit" name="options" ng-change="update_commit_level ...

Utilizing real-time communication in a microservices environment through websocket integration

I'm facing a challenging exercise that I've been handling quite well until now. The only remaining task is to integrate WebSockets into the mix. The project involves a simple voting app focused on two topics, with specific technologies designate ...

The Thinkster.io MEAN Stack guide: A blank "post" appears on the homepage. What is causing this and how can I remove it?

Currently, I am immersed in the MEAN Stack tutorial provided by Thinkster.io. At this stage, I am integrating the node.js backend with the Angularjs frontend. The functionality includes data persistence for users to add posts and upvote them. However, an ...

An issue has occurred when attempting to import ES Module for setting all values to an object

Working on a project in Angular 6, I encountered an issue with using the npm package object-set-all-values-to version 3.9.45. Here's what I did: 1- Successfully installed it using npm i object-set-all-values-to ✔️ OK 2- However, when trying to i ...

Issue with using loadChildren in Angular 11 routing

Once I log in to my app, I navigate to the link: this.router.navigate(['/sellTicket/chooseTicket']); In my app-routing configuration, I have the following setup: const routes: Routes = [ {path: 'login', component: LoginComponent}, ...

Generate a hyperlink within a paragraph

Can anyone provide tips on how to turn a string from Json into a paragraph with a hyperlink included? <p>Dumy Dumy Dumy Dumy Dumy Dumy Dumy DumyDumyDumyDumy abc.com </p> Currently, the paragraph displays as is, but I would like to make abc.c ...

Unable to incorporate .tsx files into a Node.js Web Application project

After creating a new Node.js Web Application in Visual Studio 2015, I encountered an issue with adding and compiling .tsx files to the project. Instead of being added to the actual project, the .tsx file was placed into a Virtual Project. The project is co ...

How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection. Error Occurred <inpu ...

Handsontable's unique text editor feature is encountering a tricky issue with copying and pasting

In my table, there are two columns: name and code. I have developed a simple custom editor for the code column, where the user can double click on a cell to open a custom dialog with a code editor. You can view a simplified example of this functionality he ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

Passing a dynamic value to a modal in AngularJS: A guide to enhancing user interaction

I'm attempting to send dynamic parameters to a modal by clicking a button, but some values are not being captured correctly and returning empty. Below is the snippet of my modal: <div id="<%handler%>" class="modal fade"> <div clas ...

Issue with batarang in AngularJS when using local files

Whenever I attempt to use the batarang chrome extension without a web server, it fails to work properly. The model doesn't display when loading a local file in Chrome. I have tried running Chrome with the --allow-file-access-from-files parameter and e ...