The properties defined in the typescript model become inaccessible once the data is transferred to a different webpage

I've created a TypeScript model within my Angular application and initialized an object with that model. However, when passing the object through routing to the second component (UserComponent), the associated types are not available as shown in the image. Below are the relevant code snippets. You can also find the StackBlitz demo at: https://stackblitz.com/edit/tsmodel-test

Model

export class UserModel{
  name: string;
  id: number;
}

1st Component

export class HelloComponent  { 
  user = new UserModel(); 

  constructor(private router: Router){}

  ngOnInit() {
    this.user.name = 'abdc';
    this.user.id = 23232
    console.log(this.user)
  }

  btnClick() {
    this.router.navigate(['user'], { state: {data: this.user} });
  }
}

2nd Component

export class UserComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}
  user;
  ngOnInit() {
    console.log('Component2')
    console.log(history.state.data);
    this.user = history.state.data;
  }
}

Output

https://i.sstatic.net/kf4HW.png

Answer №1

One reason for this is that the type of history.state.data is 'any.' It is not limited to a specific data type as it is arbitrary. If you wish to access the data as a UserModel, you can update your user.component.ts file as follows:

 user: UserModel = new UserModel();
 ngOnInit() {
    this.user = history.state.data;
  }

Please note: there are better ways to pass data between components than using the state data

Update

user: UserModel = new UserModel();
  ngOnInit() {
    this.user = Object.assign(new UserModel, history.state.data);
    console.log(this.user);
  }

Answer №2

When examining the console, you'll notice that the TypeScript type is not visible, instead you'll see the JavaScript class UserModel. At this point, you attempt to access the state of the History object, which appears to be a duplicate of the original object (further investigation needed). This method of passing objects between two components is not recommended.

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 ngx-translate: Responding to language change event

Is it possible to detect the change in the "current language" using the ngx-translate library? Which JavaScript event should I use to accomplish this task? To clarify, please refer to this straightforward example: https://stackblitz.com/edit/github-yvbmgu ...

What is the process for monitoring a property in Angular?

Seeking clarification on Angular - is it possible to detect property value changes within the same class? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', ...

Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false) const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') const [errorUsername, setErrorUsername] = React.useState(true) const [er ...

Angular Error: "Provider's ngAfterViewInit method is not defined at callProviderLifecycles"

I encountered an error: evt = TypeError: provider.ngAfterViewInit is not a function at callProviderLifecycles while working on my Angular project. What's strange is that I do not have an ngAfterViewInit method, nor do I have the corresponding impl ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

Unlocking Security in Angular 2

I am struggling with the issue of security in Angular 2. I am attempting to calculate the width of a span element within an ngfor loop: <span style="width:updateStyle({{ ((date | amDifference : item.startdate : 'minutes' :true)/item.duratio ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Next.js focuses solely on rendering markup and does not run any custom code

I am in the process of creating a website, where currently the only functionality available is to change themes by selecting an option from a dropdown menu (the theme is an attribute that uses CSS variables). Everything was functioning properly, however t ...

TSLint throws an error, expecting either an assignment or function call

While running tslint on my angular project, I encountered an error that I am having trouble understanding. The error message is: expected an assignment or function call getInfoPrinting() { this.imprimirService.getInfoPrinting().subscribe( response => ...

What could be causing my mdx files to not display basic markdown elements such as lists and headings? (Next.js, mdx-bundler)

Trying to implement Kent C Dodds mdx-bundler with the Next.js typescript blog starter example is proving challenging. While it successfully renders JSX and certain markdown elements, basic markdown syntax like lists and paragraph spacing seem to be malfunc ...

Execute a chain of consecutive HTTP requests and receive an Observable in response

I am currently working on two observable request functions that need to run sequentially in order for the desired outcome. Although it is functioning, I am facing an issue where the print function needs to be executed after the newOrder api call and return ...

What is the process for assigning custom constructor parameters to an Angular Service during its creation in an Angular Component?

I have been tasked with converting a Typescript class into an Angular 6 service: export class TestClass { customParam1; customParam2; constructor(customParam1, custom1Param2) { this.customParam1 = customParam1; this.customPara ...

Utilizing NGRX reducers with a common state object

Looking for a solution with two reducers: export function reducer1(state: State = initialState,: Actions1.Actions1); export function reducer2(state: State = initialState,: Actions2.Actions1); What I want is for both reducers to affect the same state objec ...

Modify an array by incorporating values from another array that have a matching property

I have two arrays that look like this let array1 = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': ' ...

Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type? type Five = Number<'5'> // `Five` is con ...

What is the term for specifying a variable's data type using a set of values instead of a traditional type?

Recently, I stumbled upon some code that introduces a class with specific variables defined in an unconventional manner. export class Foo { id: string = "A regular string" bar: '>' | '<' | '=' | '<=' | ...

Creating a new project in ASP Net Core Angular using Bootstrap 4 for the SideMenu layout instead of Bootstrap 3

I am currently working on developing a website using Angular6, where I aim to have a vertical navbar for large screens and a top navbar with dropdown functionality for mobile devices. While searching online, I came across several examples that seemed overl ...

Angular 7: Exploring the Best Way to Modify Query Parameters While Subscribing

When attempting to convert query parameters to integers within a subscription, I am encountering an issue where the code stops executing after any transformation of query parameters. This occurs regardless of whether the parameters are transformed to integ ...

Update the response type for http.post function

I've implemented a post method using Angular's HttpClient. While attempting to subscribe to the response for additional tasks, I encountered the following error: Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{}, ...

The module 'three/examples/jsm/controls/OrbitControls' or its corresponding type declarations could not be located

In my React project, I am utilizing TypeScript and three.js, where I'm importing OrbitControls in the following manner: import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; How ...