[英]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.