Preserving variable values across page transitions in Angular 2

I am facing an issue with my multi-page website that uses a router. I want to pass a variable value from one page to another.

Here is the code snippet from my contact form page:

testName:string = "hello";

ngOnInit()
{       
    this.dataService.Stream
        .subscribe(
            (city:City) => this.processData(city),
            (err) => console.log('Error at processing data'),
            () => console.log('Complete...')
        )
}

processData(city:City)
{
    console.log('the city name is: ', this.testName);
    this.problematicCity = city;
    this.testName = city.name;
    console.log('received data for city: ', this.testName);
}

When I send a city from the main page to the data service, the console output is:

the city name is: hello
received data for city: Luxemburg

However, when I navigate to the contact page, the testName variable reverts back to 'hello'.

I am trying to find a way to prevent this from happening. I attempted not initializing testName, but it resulted in the error:

assignment to undeclared variable string
.

Moving testName:string = "hello"; to ngOnInit also gives the same error.

Additional Information: This is the code for my data service:

//data.service.ts
import {Subject} from 'rxjs/Subject';
import {Injectable} from 'angular2/core';
import {City} from '../model/city.model';

@Injectable()

export class DataService
{
    Stream:Subject<City>;

    constructor()
    {
        this.Stream = new Subject();
    }
}

Answer №1

When you implement a Subject, you are essentially creating a proxy that acts as both an observer and an observable.

However, if you decide to create a [Behavior|Replay]Subject, you are generating a hot stream, meaning that any new observer subscribing to it will immediately receive the most recent value available.

On the other hand, a cold stream, such as HTTP calls, transmits the entire stream once subscribed to and does not maintain the subscription once the data has been received.

Basically, each time you instantiate a new contact component, a new subscription is created, and the subscription code is executed whenever you call next on your subject OR when you establish a new subscription (hot streams fetch the most recent value of the stream upon initial subscription).

To prevent this behavior, you have the option to either restrict your subscription to a single call or delete your subscription when the component is destroyed. The latter option is advisable:

ngOnInit() {
  this.streamSubscription = this.dataService.Stream.subscribe(...);
}

ngOnDestroy() {
  this.streamSubscription.unsubscribe();
}

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

Utilize Angular's $state service within a configuration setting to automatically redirect to a specific state using an interceptor

I'm working with restangular and have set up an interceptor to handle 401 responses by redirecting to another state. The issue is that angular only allows the injection of providers, not services, in config. Is there a way to access the $state: ng.u ...

TRPC error: The property 'useInfiniteQuery' is not found in the type '{ useQuery'

Issue with TRPC I am facing a problem with my tweetRouter that has a timeline query returning tweets and a NextCursor. However, I encounter an error when trying to access useInfiniteQuery in my components. ** Property 'useInfiniteQuery' does no ...

Angular - What causes variables to lose data after component changes?

Having an issue with two components - one creating and changing an array, and the other getting the array. The problem is that when retrieving the array in the second component, it only shows the default empty data. Code for array creation: export cla ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

TS: Utilizing a generic parameter in an overloaded function call

This piece of code encapsulates the essence of what I'm trying to achieve more effectively than words: function A(a: string): string; function A(a: number): number; function A(a: any) { return a; } function B<T extends number | string>(arg: T): ...

Securing API keys in an Angular 2 client-side application: Best practices

Currently, I am working on an Angular 2 project and facing the challenge of making API calls from my service without exposing the keys. While it is recommended to use keys from the backend, I wonder if there is a secure way to handle this directly from th ...

Having trouble with Angular 5's Post function?

Having some trouble with my Angular 5 application and API calls. For some reason, when I add headers to the request, the browser is not recognizing them properly and showing 'OPTION' instead of the actual headers. This is resulting in a 403 respo ...

Assessing functionality in Angular8 by testing a function that accesses an array from a service

I have a function that I want to test along with the current test setup: canShowIt() { let showit = false; const profils = this.requestsService.userProfil; showit = profils.some((profil) => profil.id === this.profileDetail.id); return showit; ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

Tips for patiently waiting for a method to be executed

I have encountered a situation where I need to ensure that the result of two methods is awaited before proceeding with the rest of the code execution. I attempted to use the async keyword before the function name and await before the GetNavigationData() me ...

Angular is putting the page on ice - all clicks are officially off limits

When making an HTTP request to the backend in my project, I need the ability to sort of "freeze" the screen until the request is complete. Specifically, I want to prevent users from being able to interact with certain elements on the page, such as a butt ...

Issue with Angular 2+ removeAt method not functioning properly within a nested component

Currently, I am utilizing model-driven approach for the form in angular4. I have passed a formarray to the child component using @input. However, whenever I try to use removeAt function on it, it throws an error: removeAt is not a function This is wha ...

Learn the process of transferring a complete JSON object into another object using Angular

I'm having trouble inserting one object into another. My JSON object is multidimensional, like this: { "item1":{ "key":"Value", "key":"Value" }, "item2":{ "key ...

Incorporate personalized No Data Available message in ngx-datatable

How can I customize the no data message for ngx-datatable? I want to avoid displaying the default message that comes with it. Here is what I have attempted so far: <div *ngIf="showTable"> <ngx-datatable [rows]="rows"> ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises wh ...

Testing TaskEither from fp-ts using jest: A comprehensive guide

Entering the world of fp-ts, I encounter a function (path: string) => TaskEither<Erorr, T> that reads and parses configuration data. Now, my challenge is to create a test for this process. Here is what I have tried so far: test('Read config& ...

The error that has occurred is: `TypeError: The object on the right side of the 'instanceof' keyword is

Testing my function that verifies if a variable is an instance of a specific type and performs an action has been successful. I conduct the verification using the following code: myCheckingFunction = () => { if (target instanceof H.map.Marker) { ... ...

Is there a specific type of function missing in Typescript?

I am facing a challenge in converting an existing JavaScript code to Typescript. The original javascript code is as follows: object.getsomething( function(err, result) { // async }); I am confused about how to properly type the parameter "function(er ...

Issue with Angular 10: Modal window fails to open upon second click

Encountering an issue with a Modal window overlapping the navigation bar and overlay due to a third-party bundle.js adding dynamic classes and divs under the parent-container. The problem arises from a fixed positioning of one of the classes which causes t ...

access denied on image links

While developing a web app with Angular5, I encountered an issue regarding retrieving image URLs from the 4chan API. Each post in my database contains an image URL, however, when I try to access it through my app, I receive a 403 forbidden error in the con ...