Prevent Promise / Property not found error in Angular2 by Instantiating Class

When working with my "export class", I encountered an issue that led to a Promise error if I didn't include this line of code:

purchase = new Purchase();

right before the constructor. The error indicated that the property "name" was not found.

Although my HTML Template is set up to bind to the "purchase" class with:

<h2 text-center><input [(ngModel)]="purchase.name"></h2>

I expected the class to be provided by the Service Injector in the Constructor. However, explicitly declaring the structure of the "purchase"-class in the Detail Controller could pose challenges during unit testing.

Are there any suggestions on how to avoid the need for "purchase = new Purchase()"?

For reference, here is the complete code snippet:

import {Component, OnInit} from "@angular/core";
import {PurchaseService} from '../../services/purchase.service';
import {Purchase} from '../../services/purchase';

@Component({
  templateUrl: 'build/pages/detail/detail.html',
  providers: [PurchaseService] // teach injector how to make a PurchaseService
})

export class DetailPage implements OnInit{

  name: String;
  purchase = new Purchase();

  constructor(
    private _navController: NavController, 
    private _navParams: NavParams, 
    private purchaseService: PurchaseService) {

      this._navController = _navController;
      this.name = _navParams.get('name');
  }

  ngOnInit() {
    this.getOnePurchase();
  }

  getOnePurchase() {
    this.purchaseService.getOnePurchase(name)
        .then(result => this.purchase = result
        )
        .then(result => console.log(result)
        )
  }

  pushPage(name: string) {
    this._navController.pop();
  }
}

Answer №1

Eliminate the new Purchase() function and update your template to:

<h2 class="text-center"><input [(ngModel)]="purchase?.name"></h2>

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

Challenges arise when dealing with generics in TypeScript

I'm a beginner in TypeScript and I'm trying to write a method with a generic type argument similar to what you can do in .Net. Here's the code snippet I've been working on: class TestObject { Id: number; Truc: string; Machin: str ...

Tips for importing a file with a dynamic path in Angular 6

I'm facing an issue where I need to import a file from a path specified in a variable's value. For example, it looks like this: let test = require(configurationUrl); Here, configurationUrl represents a path such as '../../assets/app.conf.j ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

Dealing with permission-based errors on the interface

I've been working on implementing authorization in my Angular project for hours now, following this example. I have created an HTTP interceptor to handle errors, but I'm unsure how to display these errors in my login view. I have tried passing a ...

Angular 7 and its scrolling div

Currently, I am working on implementing a straightforward drag and drop feature. When dragging an item, my goal is to scroll the containing div by a specified amount in either direction. To achieve this, I am utilizing Angular Material's CDK drag an ...

What could be causing my project to install an erroneous Angular version?

It appears that my project is not utilizing the latest Angular code, but I am unsure of the reason behind this. I have checked my package.json file and found the following dependencies: "devDependencies": { "@angular/common": "2.0.0", "@angular ...

Leverage the source code of Angular 2 in your project for seamless integration

Currently in the process of setting up Angular with npm: npm install @angular... Encountering an issue where the TypeScript source files are not included. I would like to have access to debug the code using the TypeScript source files (with source maps). ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

How can a secondary property type be determined by the key utilized in another property?

My goal is to develop a filter type that uses the primary object type to specify a set of keys for "field" and then assigns the appropriate type to the "value". However, I have encountered challenges in achieving this as the best outcome I could attain w ...

Tips for patiently waiting for a function that is filled with promises

Consider the following function: const getData = () => { foo() .then(result => { return result; }) .catch(error => { return error; }); }; Even though getData does not directly return a promise, it internally handles asynchro ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

Encountering difficulties importing an NPM library into StackBlitz

Hey there, I'm currently attempting to replicate an Angular example online but am encountering issues importing my Tabulator Library in stackblitz. I keep receiving an error when trying to import it in the hello component. import Tabulator from &apo ...

Encountered a Runtime Error: Uncaught promise rejection - couldn't locate removeView

I am facing an issue with calling two API calls on the same page. When I use only one API call, everything works fine. However, when I try to make two API calls on the same page, I encounter the following error at runtime: Error Uncaught (in promise): r ...

What are the best ways to utilize @types/bootbox and @types/jquery?

Is there a way to incorporate @types/bootbox and @types/jquery into an Angular 4 project? I attempted the following: npm install @types/bootbox and in my code, I am implementing it like so: import * as bootbox from 'bootbox'. However, I encou ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

Setting up Material-UI for React in conjunction with Typescript: A step-by-step guide

I've encountered issues while trying to integrate Material UI into my React project that's written in Typescript. Following the tutorial, I began by adding the react-tab-event-plugin. import injectTapEventPlugin from 'react-tap-event-plugi ...

Fixing the issue "Unable to access property 'toDataURL' of undefined" in the Angular2 signaturePad

I am currently developing a project using Angular 7 and I am facing an issue with implementing signature functionality. I decided to use the "angular2-signaturepad" package for this purpose, and everything is working smoothly until the user completes drawi ...

Creating hyperlinks to files dynamically in Angular can be easily achieved by utilizing JSON $ref

My Angular website includes a Bootstrap card that utilizes *ngFor to display a title, document name, and extension. Here is an example: https://i.sstatic.net/wi2Zx.png I would like the "handbook_2017.pdf" to be a clickable hyperlink that opens or downloa ...

How come the Angular 2 router is updating the template but not the URL after a manual change?

I have a few different paths in my application setup: [ { path: "admin", component: ContentComponent, canActivate: [ CanActivateIfAuthenticated ], children: [ { path: "", path ...