[英]GET() communication between Angular and Node JS
我有一个带有 Typescript 的 Angular 和 Node JS 项目,我试图在其中使用服务创建它们之间的通信。
从前面发出 get() 请求时,我无法从后面得到任何东西,我不知道我可能缺少配置什么或服务中有什么问题。
这是 API 响应:
这是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}`);
}
}
这是我试图在控制台上显示消息的 component.ts:
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())
}
}
这是我在控制台上得到的:
我应该如何做 GET() 请求来与后面通信?
您正在订阅,但随后对订阅什么也不做。 我建议您多阅读有关角度订阅的内容,但实际上您想要做的是从订阅中获得结果,就像这样。
items: string[];
this.dashboardService.getTest().subscribe({
next: result => items = result,
});
您的服务中的 get 方法也需要一些工作。
public getTest(): Observable<string[]> {
return this.http.get<string[]>(`${this.url}`);
}
这是用于返回字符串列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.