简体   繁体   中英

GET() communication between Angular and Node JS

I have an Angular and Node JS project with Typescript in which I am trying to create the communication between them using a service.

When making a get() request from the front I can't get anything from the back, I don't know what I might be missing to configure or what problem I have in the service.

This is the API response:

在此处输入图像描述

This is the service.ts:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})

export class DashboardService {

  private url = 'http://localhost:8080/list/product'

  constructor(
    private http: HttpClient
  ) {}

  public getTest() {
    return this.http.get(`${this.url}`);
  }
}

This is the component.ts where I am trying to display the message on the console:

import { Component, OnInit } from '@angular/core';
import { DashboardService } from './dashboard.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  constructor(
    private dashboardService: DashboardService
  ) {
  }

  ngOnInit() {
    console.log('hola')
    console.log(this.dashboardService.getTest().subscribe())
  }
}

This is what I get on the console:

在此处输入图像描述

How should I do the GET() request to communicate with the back?

You are subscribing but then doing nothing with the subscription. I recomment you read up on angular subscriptions a bit more, but effectively what you want to do is get the result from the subscription like so.

items: string[];

this.dashboardService.getTest().subscribe({
     next: result => items = result,
});

Also your get method in your service needs a bit of work.

  public getTest(): Observable<string[]> {
    return this.http.get<string[]>(`${this.url}`);
  }

This is for returning a list of strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM