Dealing with Uncaught Promises in Angular 2 while injecting a service

I followed the instructions in the official tutorial to start a project, but I'm encountering an issue with injecting services into my Angular2 app. Everything was working fine until I added a service. Here are the files :

app.component.ts

import { Component, OnInit } from '@angular/core';

import { client }  from './client/client';
import { clientService } from './client/client.service';

@Component({
    selector: 'my-app',
    template: `
    <nav>
        <h1>{{title}}</h1>
        <h2>client n° {{client.id}}</h2>
    </nav>
    <client-detail [client]="client"></client-detail>
    `,
    providers: [clientService]
})

export class AppComponent implements OnInit { 
    title = "client gendarmerie";
    client: client;

    constructor(private clientService: clientService) { }

    getclient(): void {
        this.clientService.getclient().then(client_eg => this.client = client_eg);
    }
    ngOnInit(): void {
        this.getclient();
    }
}

service/client.service

import { Injectable } from '@angular/core';

import { client } from './client';
import { client_EG } from './mock-client';

@Injectable()
export class clientService {
    getclient(): Promise<client> {
        return Promise.resolve(client_EG);
    }
}

client/mock-client

import { client } from './client';

export const client_EG: client = {
    id:parseInt('10243'),
    contact: {
        phone: parseInt('0606060606'),
        access: ["Localisation", "chat", "picture"]
    },
};

Before adding the service, everything was running without issues. However, when I try to launch the app, I encounter the following error:

core.umd.js:3462 EXCEPTION: Error in ./AppComponent class AppComponent
- inline template:3:12 caused by: Cannot read property 'id' of undefinedErrorHandler.handleError @ core.umd.js:3462(anonymous function) @ core.umd.js:6860ZoneDelegate.invoke @ zone.js:203NgZoneImpl.inner.inner.fork.onInvoke @ core.umd.js:6242ZoneDelegate.invoke @ zone.js:202Zone.run @ zone.js:96(anonymous function) @ zone.js:462ZoneDelegate.invokeTask @ zone.js:236NgZoneImpl.inner.inner.fork.onInvokeTask @ core.umd.js:6233ZoneDelegate.invokeTask @ zone.js:235Zone.runTask @ zone.js:136drainMicroTaskQueue @ zone.js:368ZoneTask.invoke @ zone.js:308 core.umd.js:3464 ORIGINAL EXCEPTION: Cannot read property 'id' of undefined

Answer №1

When the view undergoes its initial change detection tick, it attempts to evaluate the client.id expression, but the value of client is currently undefined. This is because the promise for the getclient method has not been resolved yet.

An alternative solution would be to use the Elvis Operator like client?.id, and then utilize the ngIf directive to hide the client-detail Component until the client object is populated.

Markup

<nav>
    <h1>{{title}}</h1>
    <h2>client n° {{client?.id}}</h2>
</nav>
<client-detail *ngIf="client" [client]="client"></client-detail>

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

Transmit information between components through a form

Is there a way to transfer data from one component to another in Angular? I have two components set up and I am currently using a selector to display the HTML content in the first component. Now, I need to figure out how to send the data entered in a form ...

The recent update to Angular 2 rc 1 router has caused some issues with the subscribe function not receiving

During Beta 17, the URL was passed to the subscriber in this manner: this.router.subscribe(function(url){ if( typeof url !== "undefined" ) { if( url.length > 0 ) { console.log('Handle router changes /' + url); ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

The behavior of Angular 4 router is causing components to accumulate on routerLink navigation rather than being properly removed

While transitioning from a submodule's child route to another sibling child route, the router does not destroy the previous component. Instead, it appends the new one on forward and backward navigation. What causes this behavior? It begins in /#/sub ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

If you try to paste the same value into the Input field a second time, the two-way data binding fails to update

Looking for help with an input tag: <input type="number" [ngModel]="position" (ngModelChange)="onChangePosition($event)" /> The onChangePosition function is set up to trim the input value to 3 numbers if it exceeds that length. For example, when e ...

TypeScript is encountering difficulty locating a node module containing the index.d.ts file

When attempting to utilize EventEmitter3, I am using the following syntax: import EventEmitter from 'eventemitter3' The module is installed in the ./node_modules directory. It contains an index.d.ts file, so it should be recognized by Typescrip ...

What is the best way to globally incorporate tether or any other feature in my Meteor 1.3 TypeScript project?

I've been working hard to get my ng2-prototype up and running in a meteor1.3 environment. Previously, I was using webpack to build the prototype and utilized a provide plugin to make jQuery and Tether available during module building: plugins: [ ne ...

How to prevent right-clicking on an entire website using Angular, not just specific pages

I have been searching for a solution to disable right-click on my entire Angular 2+ application, but all I can find are solutions that only work for specific components such as, <someSelector appDisableRightClick></someSelector> Where "someSel ...

What is the correct way to invoke a function from a separate file in typescript?

I am new to typescript and still learning. I have a question regarding calling a function defined in file B from file A. Can someone guide me on how to achieve this? ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

becoming a member of cdk scroll strategy notifications

In the process of creating a unique service that generates cdk overlays, I am faced with the challenge of listening to cdk scroll strategy events. Specifically, I am interested in detecting when the cdk closes an overlay using the "close" scroll strategy. ...

No information is being emitted by the subject

In my application, I have a feature where users input data that needs to be validated in a form. Once the validation is successful, a button is enabled allowing the user to submit their order. However, I'm facing an issue with this specific component ...

I encountered TS2345 error: The argument type X cannot be assigned to the parameter type Y

Currently, I am delving into the world of Angular 8 as a beginner with this framework. In my attempt to design a new user interface with additional elements, I encountered an unexpected linting error after smoothly adding the first two fields. The error m ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

The data in the object bound to [ngmodel] does not update properly when changed within a method

Hello everyone, I am in need of some assistance with a puzzling issue. Currently, I am generating a set of inputs using JSON. When I make changes to the data in the web interface, everything works fine. The problem arises when I try to modify the value ...

Error message in TypeScript with Puppeteer library: "Element not found"

Incorporating puppeteer-core as a dependency in my TypeScript project within Visual Studio 2019 has caused an issue during the build process. The error message displayed is shown by a red squiggly line under Element: https://i.stack.imgur.com/HfJCu.png ...

Maximizing the potential of process.hrtime.bigint

Whenever I include the following code: const a = process.hrtime.bigint(); The linter says it's okay, but during compilation, I encounter this error message: error TS2339: Property 'bigint' does not exist on type 'HRTime'. This ...

Challenges faced with the Nativescript Software Development Kit

I am currently working on a Nativescript app with Angular and using a JSON server. However, I am facing some errors when I try to run 'tns run android' or 'tns doctor' commands. × The ANDROID_HOME environment variable is either not se ...