Sending information from one component to another may result in the data becoming undefined

Using a service to transfer data between components in an article.

Learn more about passing data between two components in Angular 2

export class SendService {
  constructor(
    private router:Router,
  ) { }
  private data;
  setData(data){
    this.data = data;
  }
  getData(){
    let temp = this.data;
      this.clearData();
    console.log('result is ',temp);
    return temp;
  }
  clearData(){
    this.data = 0;
}

Sender component's data value can be either 1 or 0.

sender(data){
    this.transfereService.setData(data);
  }

Received component:

ngOnInit() {
    this.data= this.transfereService.getData();
  }

When changing the page in HTML, users gain access to some menu based on data being equal to 1.

However, there is a problem - when refreshing the page, the data value becomes undefined. How should I handle this?

Answer №1

Upon refreshing the page, all data will be reset and the data variable will become undefined. In your service, you have declared the data variable but not initialized it with any value. To prevent getting an undefined error, make sure to initialize the variable as shown below.

export class SendService {
  constructor(
    private router:Router,
  ) { }
  private data = 0; //updated line
  setData(data){
    this.data = data;
  }
  getData(){
    let temp = this.data;
      this.clearData();
    console.log('result is ',temp);
    return temp;
  }
  clearData(){
    this.data = 0;
  }

To address this issue, I am presenting a concept using local storage for persistence even after reloading the page. You can refer to this example - stackblitz for local storage example

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

Properly cancel subscriptions using post, put, patch, or delete requests in Angular

I'm curious about the most effective method for unsubscribing a post, put, patch, or delete on the HTTP service. For instance, take this method that is called in a page to save an object: public add(obj) { const sub = this.service.post('/path/t ...

Finding the value of an item within a JSON sub-array based on the most recent date that falls within a specified timeframe

I am currently developing a billing application using Angular. The items array that I am working with is structured like this (showing only one item here):- items: [{ _id: "5ee2298f59ce2e1747cb5539" createdAt: "2020-06-11T ...

Navigating session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

Using Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property. No error code present: import {model, mo ...

Angular module federation encountered a problem with injecting dependencies without sharing, resulting in an

I am facing an issue with my Angular 12 microfrontend applications. When I share core components like this: shared: { '@angular/core': { eager: true, singleton: true }, '@angular/common': { eager: true, singleton: true } ...

What is the process behind the functioning of Typescript Annotation Scan?

I've been tackling a project that involves using annotations to implement routing for an express API app. However, I'm running into a problem where the route list is coming up empty at runtime. Despite trying various resources, I haven't be ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Using an Angular Promise and Conditional Statement for Authentication Guard

I am trying to implement a guard that determines whether a user can access the login page, but I suspect my approach is flawed due to my use of Promises. Here is the relevant code snippet: canActivate(): boolean | Observable<boolean> | Promise<b ...

Are `import type` and `import()` the same thing?

Is there a difference between? import type { Foo, Bar as Baz } from './' and type Foo = import('./').Foo type Bar = import('./').Baz It's important to note that the import() here is not a dynamic import but rather impor ...

A guide on retrieving the values of all child elements within an HTML element using Puppeteer

I have been exploring the capabilities of puppeteer and am trying to extract the values from the column names of a table. <tbody> <tr class="GridHeader" align="center" style="background-color:Black;"> <td cl ...

Steps for generating a docker-compose.yml configuration file with jib integration

I have generated an image using the jib plugin, but now I need to use docker-compose which requires a Dockerfile. How can I connect my existing jib image to docker-compose in order to build my backend application seamlessly? ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

Stay tuned for updates in Angular's database after adding or updating entries

Currently, I am utilizing this code in my component to listen to the API: constructor(){ this.userService.listen().subscribe( (m: any) => { this.getCurrentMateriDetail(); } } ) } getCurrentMateriDetail() { return t ...

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

Utilizing generics with Swagger in NestJS

export class PaginatedResult<T> { @Expose() @ApiResponseProperty(type: T}) // It's unfortunate that this isn't working because it's a type but being used as a value @Transform(({ obj }) => obj.data.map((data) => new obj.cla ...

Distinguish between two varieties using parameters

Let's consider the following simplified example: type Reference<T extends {identifier: string}> = T['identifier'] In this type, TypeScript recognizes that it is a reference to an object where the identifier property is of type string ...

Using an enum with [routerlink] in Angular 7 is a great way to navigate

Enum Example: export enum InternalLinks { Home = '/home', About = '/about' } In the HTML of my CustomComponent, I have this: <div class="link-container text-right"> <a [routerLink]="InternalLinks.About" class="text-b ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

Using CreateMany within a Prisma Create query

Hello, I have been working on implementing a create statement that accepts an array of another model. Below are my schemas: model House { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt property_name String ...