我是Angular的新手,我仍然不太了解它的工作原理。我从自己构建的API中提取了数据。之所以有效,是因为我在邮递员中进行了测试。我无法在我的有角度的应用程序中显示它们,我也不明白为什么。
我的api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private SERVER_URL = 'http://localhost:8080/returnShelf';
constructor(private httpClient: HttpClient) { }
public get() {
return this.httpClient.get(this.SERVER_URL);
}
}
我的home.component.ts:
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
books = [];
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.get().subscribe((data: any[]) => {
console.log(data);
this.books = data;
});
}
}
我home.component.html:
<div style="padding: 13px;">
<div *ngFor="let book of books">
<h2>{{book.title}}</h2>
<p>
{{book.author}}
</p>
</div>
</div>
有人可以解释为什么我仍然无法显示我的图书数据吗?
Ok,我浏览了一下互联网,问题是我的后端没有映射CORS。
该解决方案包括通过以下方式在ApiApplication.java中添加corsConfigurer:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:4200");
}
};
}
感谢大家的支持!
您可以尝试这个吗?在src文件夹中创建proxy.conf.json文件,并添加以下内容:
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
接下来,打开angular.json文件,并在serve->选项下添加一个proxyConfig项,该项指向src / proxy.conf.json文件,如下所示:
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json"
},
...
}
}