Angular service fails to change the object's value

Currently, I am working on a service that is responsible for setting and getting the value of an object. The issue I am facing is that even though I am successfully sending the value to the setter function, when I try to retrieve it later, the values remain unchanged. Can someone please review the code snippet below and help me identify what could be causing this persistence of old values? (Note: I have omitted some component headers and imports for brevity.)

//service.ts
export class NavService {

   private location;

   constructor(){

       this.location = {
          next:'',
          back: ''
       }
   }

   setLocation(back:string, next:string){
      this.location.next = next;
      this.location.back = back;
   }

   getLocation(){
     return this.location;
   }

}

In my view, there is a button that triggers either the next() or back() functions to update the location.

export class PlanComponent {

   location;
   currentPage : string = 'start';

   constructor(private nav:NavService){}

  forward(){
     this.location = this.nav.getLocation();
     this.currentPage = this.location.next;
   }

 }

When loading a new location which loads a new component, the new component should set the new location. However, in the parent component, attempting to get the location still provides the same old values.

 export class AboutComponent {

    constructor(private nav: NavService){
       this.nav.setLocation('start', 'about');
   }
 }

Your time and attention in reviewing this matter are greatly appreciated!

Answer №1

One reason for this behavior could be related to the life-cycle of NavService. Your component may receive a new instance of the service each time it is created. To ensure consistency, make sure that the NavService is provided at the top level component or module:

@NgModule({
    /* ... */
    providers: [
        NavService
    ]
    /* ... */
})
export class AppModule {
}

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

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

The value is not being displayed by ngModel

When working with HTML, I encountered an issue where the ngModel was not displaying even though the selectedValueModel was already assigned. I also tried using [ngValue], which resulted in the value being passed as undefined to my ngModelChange function. ...

Exploring Ngrx: Leveraging a single selector to choose multiple property modifications

I need some help with my reactive Form Angular application that uses the NGRX store. Instead of subscribing to the entire state, I want to subscribe to changes in specific fields like "name" and "city." I have been attempting to use the selector selectFor ...

What is the reason behind the use of the ";" instead of "&" for passing query parameters in Angular8 routers?

Is there a way to implement route navigation using router.navigate similar to this example? this.router.navigateByUrl(`enrollment?id=${student.id}&request=${"delete"}`); I attempted using this.router.navigate(['enrollment',{id:student.id}]) ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Difficulty encountered when hosting an Angular and .Net Core application on a virtual machine's localhost

Having trouble running an application from a virtual machine on Azure? I'm facing an issue that I can't seem to solve. The application's front end is Angular and the backend is .NET Core 3.1. I'm using ngrok to tunnel my virtual machine ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

What is the best way to update the value of an input in a child component?

I have two files named person-input.ts and person-input.html What I want to achieve is that when inside the AddPerson function in person-input.ts, I would like to dynamically modify the name-input component by setting [focused]="true" So, the code needs ...

Discovering the root cause of an Angular binding failure

In my Angular application, I have implemented support for multiple browser tabs using angular-redux @select and {{ property }} bindings. Everything was working fine until I decided to configure my angular store with the redux-state-sync middleware to use b ...

The build error TS1036 is thrown when a function with a return statement is moved to index.d.ts, even though it worked perfectly in a standard TS file

In my project using Node v14.x and StencilJS (React) v2.3.x, I encountered an issue with a test-helper file containing a function that converts string-arrays to number-arrays: export function parseNumericStringOrStringArrayToIntegers(value: string | (strin ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Loading only specific HTML list elements in segments

Within my Angular4 application, I am faced with a challenge involving a large list of li elements. The browser struggles to handle the thousands of li's being displayed when the user interacts with the ul element. This results in slow loading times an ...

Detecting the language of a browser

In my Angular2 application, I am looking to identify the browser language and use that information to send a request to the backend REST API with localization settings and variable IDs that require translation. Once the request is processed, I will receive ...

I recently updated all my projects to Angular 14, but when I tried to install a package using `npm i`, it still

The challenge at hand I encountered an issue with my two Angular projects. The first project serves as a library utilized by the second project. I recently upgraded both projects to Angular 14 following this guide. However, after running an npm i on the ...

Upon clicking the button, the Angular Mat-Table with Reactive Forms fails to display any data, instead adding a blank row accompanied by errors

When the AddRow_click() function is executed, I populate the insuranceFormArray and assign its values to the datasource. However, after adding an entry, an empty row appears in the table, and error messages are displayed in the console. Only a subset of th ...

Where is the optimal location for placing a JavaScript listening function within an Angular component?

Summary: Incorporating a BioDigital HumanAPI anatomical model into my Angular 5 application using an iFrame. The initialization of the API object is as follows: this.human = new HumanAPI(iFrameSrc); An important API function human.on(...) registers clic ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...