Error in Angular service: receiving undefined value

logdetail.service.ts

import { Injectable } from '@angular/core';
import { LogDetail } from './logdetail.model';
import { HttpClient } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class LogdetailService {

  formData:LogDetail={
    Message: null,
    CreateDate: null,
    LogType: null,
    Int: null
  };

  readonly rootUrl='https://localhost:44370/api';
  list : LogDetail[];
  
  constructor(private httpclient:HttpClient) { }

  postLogDetail(formData:LogDetail){
    return this.httpclient.post(this.rootUrl+'/Logtbs',formData);
  }

  refreshList()
  {
    this.httpclient.get(this.rootUrl + '/Logtbs')
    .toPromise()
    .then(res => this.list = res as LogDetail[]);   
  }
}

logdetail-list.component.html

<table class="table table-hover">
    <tr *ngFor="let pd of service.list">
      <td >{{pd.Message}}</td>
      <td >{{pd.Logtype}}</td>

    </tr>
</table>

logdetail-list.component.ts

import { Component, OnInit } from '@angular/core';
import { LogDetail } from 'src/app/shared/logdetail.model';
import { LogDetailService } from 'src/app/shared/logdetail.service';
import { HttpClient } from "@angular/common/http";

@Component({
  selector: 'app-logdetail-list',
  templateUrl: './logdetail-list.component.html',
  styles: []
})
export class LogdetailListComponent implements OnInit {


  constructor(private service : LogDetailService) {  }
  ngOnInit() {

     this.service.refreshList();

  }
}

Output: this.service.refreshList(); in logdetail-list.component.ts value is undefined.

I am fetching data from a web API. I have successfully inserted data. How can I display the values on the page?

Answer №1

Problem(s)

Problem 1:

@Tonbul pointed out in the comment that you are trying to access the service in the HTML component, even though it is a private variable.

<tr *ngFor="let pd of service.list">
  ...
</tr>

Problem 2:

You are trying to access the list from the LogdetayService, which is marked as private. By default, a variable without specifying any access type is considered private.

export class LogdetayService {
    list : Logdetay[];

    ...
}

Solution(s)

Solution 1: Make variables public

1.1 Set service as public

logdetay-liste.component.ts

export class LogdetayListeComponent implements OnInit {
  constructor(public service : LogdetayService) {  }
}

1.2 Set list as public

logdetay.service.ts

export class LogdetayService {
    public list : Logdetay[];

    ...
}

Sample Solution 1 on StackBlitz


Solution 2: Return result as Observable<Logdetay[]>

2.1 Return as Observable<Logdetay[]>

logdetay.service.ts

import { Observable } from 'rxjs';

export class LogdetayService {

refreshList(): Observable<Logdetay[]> {
    return this.httpclient
       .get<Logdetay[]>(this.rootUrl + '/Logtbs');
  }
}

2.2 Define the list variable and assign value in the subscribe event from the Observable

logdetay-liste.component.ts

import { Logdetay } from '../paylas/logdetay.model';

export class LogdetayListeComponent implements OnInit {
  list: Logdetay[];

  constructor(private service: LogdetayService) {}
  ngOnInit() {
    this.service.refreshList().subscribe(res => (this.list = res));
  }
}

2.3 Use list instead of service.list

logdetay-liste.component.html

<tr *ngFor="let pd of list">
    ...
</tr>

Sample Solution 2 on StackBlitz

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

Limit file upload size to less than 1MB in Angular 2 with typescript using ng2-file-upload

Having issue with my code - I can't upload a file larger than 1mb even though maxFileSize is set to 50mb. Can anyone help me troubleshoot? @Component({ moduleId: module.id, selector: 'NeedAnalysisConsult', templateUrl: 'nee ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an ...

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 ...

Angular service unit test failed to execute

I have a service that I need to test, so I created a file named 'maincause.service.spec.ts' as shown below: fdescribe('MainCauseService', () => { let injector: TestBed; let service: MainCauseService; let httpMock: HttpTestin ...

Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved? servi ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

What is the process for unsubscribing from a Firebase list in Angular2?

My code is set up to connect to a Firebase list by using the following: tasks: FirebaseListObservable<ITask[]>; constructor(private af: AngularFire) { this.tasks = this.af.database.list("/tasks"); } However, I am now facing an issue where I need ...

Issue detected in TypeScript code - "Could not locate property 'setSelectedFile' in type 'void'.ts(2339)"

Encountering a TypeScript error in my code and seeking assistance. Below are the codes of 2 files with the error message included for review. The file causing the error is named "NewPostForm.tsx". import React, { useState } from 'react&apos ...

Exploring the capabilities of combining Typescript with withStyles in the latest @material-ui/core framework

I have been working on updating some old Typescript code that was using material-ui@next to now use @material-ui/core. Typescript Version: 2.8.3 @material-ui/core: 1.1.0 I created a simple component that accepts a single prop, but when I try to use it, t ...

The functionality of Silex Middleware Authentication varies depending on whether it is being used in Postman or

As a developer with limited experience in back-end development, I have encountered a real problem despite my best efforts. I am currently using Silex as a simple backend for an Angular 2 App. I have implemented a middleware that checks whether the user ha ...

Transforming a JSON object into XML format

Currently, I am encountering an issue while attempting to convert my JSON object to XML using the xml-js library's json2xml function. When trying to implement this functionality, I keep getting an error message that states: Error: Buffer is not defin ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Accordion border in Bootstrap should be applied to all items except the first one

I am currently implementing Bootstrap accordions in an Angular application and I am facing an issue where I want to have a colored border all around each accordion panel. The problem is that by default, Bootstrap removes the top border from all accordions ...

Steps to revert table data back to its original state after editing in Angular 12 template-driven form

Currently, I have implemented a feature in my web application where users can edit table data by clicking on an edit hyperlink. Once clicked, cancel and submit buttons appear to either discard or save the changes made. The issue I'm facing is related ...

Encountering difficulties importing a component from a library into my Nx Expo React Native application

Having an issue with my Nx monorepo which contains an Expo React Native app and various libraries. The problem arises when trying to import a component from a library within the application, resulting in Error: Cannot resolve @monorepo/account-manager Wi ...