When using AngularJS 2, the class identity is lost when resolving a Promise during fetching

SUMMARY: I'm encountering an issue where I am fetching Object instances instead of Org instances from my data in Angular 2. Is there a way to retrieve Org objects directly or is this the expected behavior?

DETAILS: In my Angular 2 project, I have modified some tutorial code and here is a snippet from my org.service.ts:

getOrgs(): Promise<Org[]> {
  return this.http
    .get(this.orgUrl)
    .toPromise()
    .then(response => response.json().data as Org[])
    .catch(this.handleError);
}

getOrg(id: number): Promise<Org> {
  return this.getOrgs()
    .then((orgs: Org[]) : Org => orgs.find(org => org.id === id));
}

This is part of my resolver:

resolve(route: ActivatedRouteSnapshot): Promise<Org>|boolean {
  let id = this.authService.user.orgId;

  return this.orgService.getOrg(id).then((org: Org) : Org|boolean => {

    if(org) { // <-- Breakpoint here
      return org;
    } else { 
      this.router.navigate(['/provider/home']);
      return false;
    }

  });
}

I'm using an in-memory service to fetch my data:

export class InMemoryDataService {

  createDb() {
    let org1 = new Org();
    org1.id = 12;
    org1.donor = true;
    org1.name = 'Great Actors Theater';
    let org2 = new Org();
    org2.id = 19;
    org2.donor = false;
    org2.name = 'Sunnyside Group Home';
    let org: Org[] = [];
    org.push(org1);
    org.push(org2);
[SNIP]

Below is my Org class definition:

export class Org {
  id: number;
  donor: boolean;
  name: string = "";

  deepCopy(): Org { ... }

  equals(other: Org): boolean { ... }
}

At a breakpoint, I noticed that the fetched object resembles an Org instance with fields (id, donor, name) but lacks class methods such as equals(). It also doesn't recognize "org instanceof Org" or "typeof org" returns "object."

I would like to work with actual Org instances with class methods rather than relying on duck-typing. Is there a better approach to achieve this?

Thank you, Jerome.

Answer №1

Build a new Org object using the provided JSON data.

Here's an example:

.then(response => {
   // Check if response is valid
   return response.json().data.map(d => new Org(d))
})

Next, specify how to create an Org object within the class definition, for instance:

export class Org {
  id: number;
  donor: boolean;
  name: string = "";

  constructor(data: any) {
     // Validate the incoming data
     this.id = data.id;
     this.donor = data.donor;
     this.name = data.name;
  }
  ...
}

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

"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

The specified module '...' is identified as a non-module entity and therefore cannot be imported using this specific construct

Currently, I am facing an issue in my .tsx file where I am attempting to import a RaisedButton component from material-ui using the following code: import * as RaisedButton from 'material-ui/lib/raised-button' Unfortunately, this is triggering ...

Compiling a list of products, but the user interface needs some adjustments

Currently, I have designed a product list menu that includes a hover dropdown feature. This means that when a user hovers over a specific menu item, the corresponding list will automatically appear. However, I am facing two issues with this setup. Firstly, ...

Tips for improving DOMContentLoaded performance with Angular2

Currently, I am in the process of converting a JQuery template to Angular 2, specifically a Dashboard-like template. This website has numerous popups, each containing multiple tabs, so I decided to separate each popup into different components to keep the ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

The mat-select element is defaulting to the last value in a loop for all dropdown selections

I am working with a Mat-select tag that is inside a loop using *ngFor, and by default, it is selecting the last value for all dropdowns. <div *ngFor="let investment of data.priorInvestmentExperiences; > <mat-form-field appearance="outline" ...

angular-in-memory-web-api encounters a 404 error

I recently completed the heroes tour and now I am trying to work on something similar, but I seem to be having trouble understanding angular-in-memory-web-api. Here is a snippet of my code: clients-data.service.ts import { Injectable } from '@angular/ ...

Obtaining POST request parameters in an Express server

Below is the code snippet for adding a product using an angular service. The product is passed as the body. addProduct(product): Observable<any> { return this.http.post<Observable<any>>( `http://localhost:4401/api/products`, ...

Is it possible for a TypeScript function to be used as a React prop even if it conflicts with the function signature's in

Why does the TypeScript type checker allow a prop with a function parameter that does not strictly match the definition? For example, I have a function called callbackImpl = (str: string): number, which is passed as a React prop parameter defined as callb ...

Angular Validation for Start and End Dates

<tr> <td class="p-10"> <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Tarih" name="date" id="date" #date="ngModel" ngModel required> <mat-datepicker-toggle matSuffix [for]="p ...

Get files asynchronously and parse them concurrently using Node JS

I am currently working on a gulp task that involves downloading JSON files from GitHub and then prompting the user to enter values for configuration. An example would be downloading an .ftpconfig file and asking the user for hostname, username, password, a ...

Angular 4: Unidirectional data flow from View to Component

Struggling to secure user credentials in my Angular form due to 2-way data binding displaying encrypted values within the component. Here's the code snippet: <form> <div class="input-group"> <span class="input-group-a ...

The element type 'HTMLElement' does not contain a property named 'pseudoStyle'

Currently experimenting with adjusting the height of a pseudo element using Typescript. An error is popping up in my IDE (vscode) as I go along. This is the code snippet I am working with. // choose element let el: HTMLElement = document.getElementById( ...

Is there a way to modify an image that has been dynamically inserted in an Angular application?

I'm facing an issue with dynamically added input files in Angular. Whenever I upload a file, it changes all the images of the input files instead of just the one I want to target. How can I resolve this problem? Please help. images = [ {url: &ap ...

The export 'ChartObject' is not available in highcharts

Trying to integrate highcharts into my Angular 4 project has been a bit challenging as I keep encountering the following error: highcharts has no exported member 'ChartObject' I have experimented with different options such as angular-highchart ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

How can I reduce the delay in Angular 5 to a minimum?

The following code represents a simple request function: getItem() { return this.http .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {}) .subscribe(response => { ... }); } Depending on the duration of the ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...