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

The attribute 'commentText' is not found within the 'Comment' data type

Currently, I am immersed in building a user-friendly social network application using Angular 12 for my personal educational journey. Running into an error has left me puzzled and looking for assistance. About the Application: The home page (home.compone ...

Error encountered when installing angular 8 components due to package conflicts

Having Trouble Building .NET Core + Angular Project I have encountered an unfamiliar project that requires minor fixes. I attempted to build it with the following command: dotnet publish -c Release -r win-x64 --self-contained false --output "D:&bso ...

Tips for correctly passing the type of combineReducers: I encountered an error saying "Property '...' does not exist on type 'Reducer<CombinedState{}>"

I am currently integrating TypeScript into my react/redux project. Unfortunately, I am encountering an error that is preventing my app from loading. The issue is shown in the screenshot below: https://i.sstatic.net/HkPwo.png Within my index.tsx file, I a ...

Mockery Madness - Exploring the art of mocking a function post-testing a route

Before mocking the process function within the GatewayImpl class to return the 'mockData' payload, I need to ensure that all routes are tested. import payload from './payloads/payloadRequire'; // payload for request import {Gate ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

Leveraging the power of Angular to seamlessly update and manipulate data in Highcharts using the highcharts

Exploring the capabilities of a highcharts directive designed for angular, known as highcharts-ng. Check it out on GitHub. Encountering an issue with updating the data when using the directive. While updating the series values is successful, facing diffic ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

Is there a way to dynamically assign values to [routerLink] based on the elements in an array?

Looking to create a dynamic routing within my template. The routing values are sourced from an array that is being iterated through with ngFor. Additionally, I need to perform some transformations on these string values. Any help would be appreciated. En ...

Dynamically loading new content in an array using Angular's service

I am looking to incorporate external JSON content into my controller's scope. Currently, initializing the scope with the first ten items is working fine. However, I want to dynamically expand the scope with new items as the user scrolls. The issue ar ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

Guide on encoding base64 within an Azure DevOps Pipelines extension

I'm in the process of creating an Azure Pipelines extension using Typescript and referring to Microsoft's documentation During my development, I encountered an issue when trying to base64 encode a string using the btoa() function which resulted ...

Encountering a 500 error (Internal Server Error) while trying to connect API Laravel 5.4 with Angular 2

Every time I try to submit a form from an Angular form to my API built on Laravel, I encounter a 500 error (Internal Server Error) in the console. What could be causing this issue? Note: The backend API functions perfectly when tested with POSTMAN. This ...

Creating dynamic tags based on values is a straightforward process that involves identifying key variables

Looking to create a template that can dynamically define native HTML tags based on a variable value. I attempted using a custom directive to swap out the initially defined tag with the desired new one, similar to what is discussed here. While this approac ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

What is the best way to send parameters to an angular service or factory?

This Plunker demonstration is a great visual guide: http://plnkr.co/edit/y3uacaQSc1MbrWKfb0At?p=preview Here's the code snippet for reference: var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope,t ...

Assign the ngClick event handler to the capturing phase

Can the ngClick event handler be configured to work in the capturing phase, as discussed in this informative article? I am interested in stopping events from propagating down to child elements and then back up again when a specific condition is met for t ...

Uncovering the perfect body proportions using Webpack and SystemJS

In the process of developing an Angular2 library that needs to work with both SystemJS and Webpack, I encountered a situation where I had to detect the height and width in pixels of the body tag to set dimensions for child tags. However, the behavior of An ...

A guide on converting TypeScript to JavaScript while utilizing top-level await

Exploring the capabilities of top-level await introduced with TypeScript 3.8 in a NodeJS setting. Here's an example of TypeScript code utilizing this feature: import { getDoctorsPage } from "./utils/axios.provider"; const page = await getDo ...

Is there a way to differentiate between a plain object and a class instance in Typescript?

Specifically, I am looking to differentiate between primitive types and plain objects versus class instances. let x = {y:5} // this is acceptable class X { y = 5; } let x = new X(); // this is not permissible ...

Set values to the inner property of the object

In my configuration file, I have set up nested properties as shown below export class Config { public msalConfig: { auth: { authority: string; clientId: string; validateAuthority: boolean; redirectUri: ...