Create a functioning implementation for retrieving a list of objects from a REST API

I am looking to incorporate an Angular example that retrieves a list from a REST API. Here is what I have attempted:

SQL query:

    @Override
    public Iterable<Merchants> findAll() {
        String hql = "select e from " + Merchants.class.getName() + " e";
        TypedQuery<Merchants> query = entityManager.createQuery(hql, Merchants.class);
        List<Merchants> merchants = query.getResultList();
        return merchants;
    }

REST controller:

@RestController
@RequestMapping("/merchants")
public class MerchantController {

    @GetMapping("/list")
    public Iterable<Merchants> getMerchantsList() {
        return merchantRepository
                .findAll();
    }
}

Service:

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

  constructor(private http: HttpClient) {
  }    
  getList() {
    return this.http.get("...../api/merchants/list");
  }
}

Component:

@Component({
  selector: 'app-terminal',
  templateUrl: './terminal.component.html',
  styleUrls: ['./terminal.component.scss']
})
export class TerminalComponent implements OnInit {
  merchants: Merchant[];
  constructor(private merchantService: MerchantService,
              private router: Router,
              private route: ActivatedRoute) {
  }   

  ngOnInit() {               
    this.merchantService.getList();
  }    
}

However, when I click on the component on the web page, nothing seems to happen. Can anyone provide me with guidance on where I may have gone wrong? Perhaps my TypeScript implementation is incorrect?

Answer №1

To ensure that the HTTP request is made, make sure to invoke the subscribe method on the Observable.

ngOnInit() {               
  this.productService.fetchData().subscribe(data => {
    console.log("Received data:", data); 
  });
}    

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

Can we condense the code to create a more concise and efficient function?

Can someone help me refactor this code snippet below into a function and combine the two IF statements? Many thanks! let value = productDetails.recentPurchaseDate; if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) { value = false; } ...

How to Generate a Collection of Textfields in Angular 4

My challenge involves working with an array object that receives input from a textfield. I am looking to create a clean design where only one textfield is initially displayed, along with a '+' button next to it. When the user enters information i ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

In this guide, we will explore the process of designing unique styles for ng

What is the proper way to customize CSS for a specific element? &.ng-select-focused { &:not(.ng-select-opened) > .ng-select-container { border-color: $ng-select-highlight; box-shadow: $ng-select-box-shadow; } } The offi ...

HTML template failing to retrieve data from Angular dataSource

My goal is to import data from an Excel file into my angular application. I have successfully retrieved the data from the Excel file, parsed it to extract the necessary columns, and stored it in an array within my service.ts file. I call the service from ...

What is the proper way to create a React Context in TypeScript that accepts both a ref and a setState function as arguments?

When encountering various errors, one of them being: Type 'Dispatch<SetStateAction<null>>' is not assignable to type '() => void' My code looks something like this: import React, { ReactElement, ReactNode, useEffec ...

What is causing the transpiler to not be triggered by the code change?

My current project involves using a TypeScript backend for a Dialogflow application with fulfillment. I initially used a preconfigured project template and didn't delve into the details. I work in VS Code and never explicitly build my code. Instead, ...

What are the main challenges in resolving dependencies and implementing best practices when it comes to updating an outdated Angular NodeJS

After several months away, I am now faced with the challenge of updating and maintaining an out-of-date angular project. Seeking advice from experienced developers on how to tackle this situation. Previously, I used NPM update or upgrade commands to keep ...

The term 'Pick' is typically used to identify a specific type, however, in this particular situation, it appears to be functioning as a value while attempting to expand the Pick

I'm attempting to selectively expose certain properties from an ancestor class on my descendant class. My approach involves using the Pick utility in TypeScript. export class Base { public a; public b; public c; } export class PartialDes ...

Instructions for displaying HTML content only when data is received from the server side

Using angular 4, I have implemented a div in my HTML to display a message when data is not found. However, the issue I am facing is that this div is shown even while the data is being fetched and has not been displayed yet. Ideally, I only want this div to ...

Creating a personalized state object containing unresolved promises in React Native utilizing axios inside a custom React Hook

I'm currently in the process of creating a custom state within a custom Hook for React Native (non-Expo environment). The state I am working on looks like this: interface ResponseState { api1: { error: boolean; errorMsg?: string; ...

Discover how TypeScript's strictNullChecks feature can help you identify null values with ease in your functions

Since Javascript often requires me to check if a value is `!= null && != ''`, I decided to create a function that checks for empty values: const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => { return variable == null | ...

When I executed the npm install -g @angularcli command, I encountered an npm error with the code ENOLOCAL

On my initial attempt, I used a computer with Windows 10 and another one with Windows 8.1. Surprisingly, I encountered the same error message on both systems. The log of the error is as follows: npm ERR! code ENOLOCAL npm ERR! Could not install from "@ang ...

Avoiding loading certain images within an *ngFor loop

Is it possible to control the loading of images within an *ngFor loop in Angular? Load image with index X first Fire a function once all other images have loaded The goal is to prioritize the display of important images while optimizing bandwidth usage. ...

Issue: Pipe 'AsyncPipe' received an invalid argument '[object Object]'

I’m encountering an issue while attempting to replicate the steps from a specific YouTube tutorial. At the 8:22 mark of this video, I’m facing the following error: Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe&apos ...

Spring REST POST service is transmitting empty values for variables

I'm a beginner in Spring MVC and I've been working on exposing REST services. While my GET services are functioning properly, the issue arises when making a POST call from Postman as it sends empty null values for fields. Here's an example ...

Facing an issue with ngx quill editor malfunctioning when utilizing the cdkDrag directive from Angular Material

Having trouble with the focus on the Quill editor or typing content while using the cdkDrag directive from Angular Material. Check out my code on StackBlitz: https://stackblitz.com/edit/angular-ivy-xalouc Issue Summary: The editor is only editable when ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

When I tap on a text element, place the cursor in the input field

I want to set the focus to an input field when I click on a specific piece of text within the same page. What is the most efficient way to achieve this? I already have a function attached to the text element. Below is the code snippet that I am working wit ...