Angular 向 localhost:4200 而不是 localhost:8080 发出 Http 请求的服务

Angular Service making Http requests to localhost:4200 instead of localhost:8080

我有一个 Angular + Spring 引导项目。 Angular 项目包含向端口 8080 上的 Spring 引导应用程序 运行 发出 Http 请求的服务。当我尝试在服务中使用环境中的 apiBaseUrl 变量时,我得到如下 404 状态:

services 正在对 localhost:4200 而不是 localhost:8080

进行 Http 调用

环境:

export const environment = {
production: false,
apiBaseUrl: 'http://localhost:8080'
};

服务:

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { environment } from "src/environments/environment";
import { Student } from "./student";

@Injectable ({
providedIn: 'root'
})

export class StudentService {


private apiServerUrl = environment.apiBaseUrl;

constructor(private http: HttpClient) { }

public getStudents(): Observable<Student[]> {

  return this.http.get<Student[]>('${this.apiServerUrl}/student');

}
 //rest of code

但是当我进行更改并直接提供 url 时,一切正常。

return this.http.get<Student[]>('http://localhost:8080/student');

谁能给我解释一下,这是我的第一个 angular 应用程序,感谢您的理解

您应该使用反引号 `,而不是单引号 '

  return this.http.get<Student[]>(`${this.apiServerUrl}/student`);

为了解决这个问题,您可以通过 `` 在这一行中更改 '' this.http.get('${this.apiServerUrl}/student');

正确的代码是:

this.http.get<Student[]>(`${this.apiServerUrl}/student`);

this.http.get<Student[]>(this.apiServerUrl+ '/student');