问题描述: Angular调用Spring Boot后端不起作用
解决方法:
确保后端服务已经正确启动,并且可以通过浏览器或者Postman等工具访问到后端接口。
在Angular项目的代码中,确保已经正确设置了后端接口的URL。可以在Angular的服务文件中设置一个全局变量,用于保存后端接口的URL。例如:
export const API_URL = 'http://localhost:8080/api';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get(API_URL + '/data');
}
}
export class MyComponent implements OnInit {
data: any;
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.getData().subscribe((response) => {
this.data = response;
});
}
}
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
// ...
})
export class AppModule { }
通过以上步骤,应该可以解决Angular调用Spring Boot后端不起作用的问题。如果问题仍然存在,可以进一步检查后端接口的URL、请求方法等是否正确,并在控制台查看报错信息,以便进行排查和修复。