What could be the reason for the server returning undefined data when making a promise request?

I have been working on retrieving data from an ASP .NET Core API and then displaying it on an HTML page using Angular and TypeScript. The communication between the client and server is functioning properly, with the response being in the form of an object. I have created a model class to extract the values from this response.

However, I am encountering an issue when trying to display these values as they all appear to be undefined. It seems like the problem lies within the Promise implementation.

Here is a snippet of the response received from the server:

Id: 1
Name: "asd"
Description: "asd"
Syntax: "Typescript"
IdentityString: "karma"
LastModified: "2020-01-05T00:51:00"
Content: "asd"
FileId: 1
File: null

Below is the relevant code:

fileshare.ts

export class FileShareComponent implements OnInit {


    constructor(
    private route: ActivatedRoute,
    private service: UserService,
    private http: HttpClient
    ) {}

  ngOnInit() {
    const file: string = this.route.snapshot.queryParamMap.get('file');

    this.http.get(this.service.BaseURL + '/Share?IdentityString=' + file)
            .toPromise()
            .then(res => this.service.sharedFormData = res as ShareModel);
            console.log(this.service.sharedFormData);
  }
}

ShareModel.ts

export class ShareModel {
    Id:number;
    Name: string;
    Description: string;
    Syntax: string;
    IdentityString:string;
    LastModified: string;
    Content: string;
    FileId: number;
}

service.ts

sharedFormData:ShareModel;

fileshare.html

<pre><code class="hljs">Name:
{{service.sharedFormData.Name}}</code></pre>
<pre><code class="hljs">Description:
{{service.sharedFormData.Description}}</code></pre>
<pre><code class="hljs">Syntax:
{{service.sharedFormData.Syntax}}</code></pre>
<pre><code class="hljs">LastModified:
{{service.sharedFormData.LastModified | date: "HH:mm dd/MM/yyyy"}}</code></pre>
<pre><code class="hljs">Content:
{{service.sharedFormData.Content}}</code></pre>

Answer №1

It is advisable to move the

console.log(this.service.sharedFormData);
code snippet inside the then() block.

The current placement of this code causes it to execute before the response is received, leading to potential issues.

Additionally, it appears that your service.sharedFormData is undefined at the moment when ngOnInit() is called. This could be the reason for any error messages you are encountering. The assignment of

this.service.sharedFormData = res
occurs later in the process, similar to the situation with
console.log(this.service.sharedFormData)
. As a result, Angular may attempt to render HTML using
service.sharedFormData = undefined
before the data is actually available.

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

Is there a way to navigate to a separate homepage based on the user's login status in Angular?

My goal is to automatically redirect users to the /dashboard page once they are logged in. The default landing page is set to /home, but for logged in users, it should be redirected to /dashboard. In my user service class, I have created a sharedUser usin ...

Guide on setting the focus of an input in a form field using ngIf

I am currently facing an issue where I need to focus on a specific input in my code based on certain conditions derived from an observable. In this scenario, I have initialized a boolean to true inside the ngOnInit() method. export class InputOverviewExamp ...

Refresh Angular 6 Navbar on RouterLink Change

Having an issue with reloading the website while using angular 6 and a routerlink in a dropdown menu within my navbar. The problem arises when the routerlink does not reload the website, only changing the route. Initially, clicking a button in the dropdown ...

Jest encountered an error while attempting to parse the TypeScript configuration file

I've been working on setting up Jest with Babel and Typescript, following the guidelines provided here. However, when I run npm run test, I encounter the error message: Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js` Th ...

Dealing with circular dependencies in NestJS by using ForwardRef

Hey everyone, I've been running into a circular dependency issue with NestJS. I tried using the forwardref method, but it hasn't resolved the problem for me. // AuthModule @Module({ imports: [ forwardRef(() => UserModule), JwtModule ...

Guide on how to showcase the template by leveraging the roomList information with ngTemplateOutlet in Angular

TS roomList = [{ name: 'Room2' }] HTML <div class="Layout-body"> <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="Room1" [ngTemplateOutletContext]="{ data: dt, i: i }&qu ...

Type void does not have a property of type forEach

I've encountered similar questions before, such as this one: (forEach Typescript TS2339 "does not exist on type 'void'") Despite that, I'm still struggling to solve my specific issue. ngOnInit() { var __this = this; this ...

A guide to fetching and organizing an array of object identifiers using TypeScript

In my project, I am dealing with an array of objects named userRoles. The structure of this array is as follows: "userRoles": [ { "id": 1, "name": "Create", "description": "Th ...

Steps to retrieve the search box input value and submit it in an AngularJs component using the Enter key

I'm facing an issue where I am trying to fetch the search list using speciesName from a table. However, when I attempt to retrieve the data by pressing the enter key, it is returning an error stating that the input data is undefined. Is there a way ...

Encountering an ERROR of TypeError when attempting to access the property 'length'

I encountered the following error message: ERROR TypeError: Cannot read property 'length' of undefined at eval (webpack-internal:///./node_modules/@angular/common/esm5/http.js:163) at Array.forEach () at HttpHeaders.lazyInit ...

Minimize the size of the Vendor.js file in Angular 8

I have come across several posts discussing ways to reduce the size of the vendor.js file in various Angular versions such as 2, 4, 6, and 7, but I haven't been able to find specific information for Angular 8. When I initially created my project, the ...

Is there a way to retrieve all elements from the array with the specified type definition of item(index: number): any?

I am currently working on a React Native project, but I have a TypeScript query. The SQLite embedded database is set up and I am trying to retrieve the entire array of rows. However, I am facing an issue with the object structure. https://i.sstatic.net/74 ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

"What sets apart the usage of `import * as Button` from `import {Button}`

As a newcomer to Typescript, I am facing an issue while trying to import a react-bootstrap Button. In scenario 1: import {Button} from 'react-bootstrap/lib/Button' In scenario 2: import * as Button from 'react-bootstrap/lib/Button' B ...

"Utilizing mongoDb's $set and $setOnInsert directives for updating specific fields within nested properties

I have a file containing sub-categories { a: fire, b: { plane: fly, c: swim, d: jump, } } During upserts, I want to specifically change the "plane" category. Here is what I have attempted: const { categories, ...rest } = newRecord; cons ...

Issue with Saving Modal in Bootstrap 5: Button Does Not Function

I've been following the instructions on , but I'm facing an issue with getting the save button to work on my modal. Initially, I tried placing it within the form tag, but it ended up using the form action from the main view instead of the partial ...

Angular 2 Service's filtering functionality can be enhanced with an Array parameter

I developed a function to retrieve filtered results from a JSON dataset. getItem(id: string): Observable<any[]> { return this.http.get('path/to/my.json') .map((response) => { let results: any = response.json( ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...

Is it necessary for ng-bootstrap scrollspy to have a defined height in order to function properly?

The ng-bootstrap [ngbScrollSpy] directive I'm using in my project, as documented here, doesn't seem to be working correctly. The active item is not changing on scroll. This is the code I have: <div> <div class="sticky-top" ...

Querying Firebase's real-time database for specific sub-child data

Here is the structure of my database: https://i.sstatic.net/Tduqg.png I have successfully retrieved all the documents by querying the userId: this.orderListRef = firebase.database().ref(`/orderList`); this.orderListRef.orderByChild('userId').eq ...