我在Angular中显示API内容时遇到麻烦,而且我不知道如何对其进行修复以保持前进。 现在,我只需要在界面中查看url数据即可。 有人知道如何解决这个问题吗? 文明文件调用在game.service.ts
中创建的get方法civilizations.component.ts
import { Component, OnInit } from '@angular/core';
import { GameService } from '../../services/game.service';
@Component({
selector: 'app-civilizaciones',
templateUrl: './civilizaciones.component.html',
styleUrls: ['./civilizaciones.component.css']
})
export class CivilizacionesComponent implements OnInit {
constructor(private gameService: GameService) { }
ngOnInit() {
this.gameService.getCivilizations().subscribe(
res => console.log(res),
err => console.error(err)
);
}
}
game.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'[![enter image description here][1]][1]
})
export class GameService {
API = 'https://age-of-empires-2-api.herokuapp.com/api/v1';
constructor(private http: HttpClient) { }
getCivilizations(){
return this.http.get(`${this.API}/civilizations`)
}
getCivilization(id: string){
return this.http.get(`${this.API}/civilization/${id}`);
}
getUnits(){
return this.http.get(`${this.API}/units`);
}
getUnit(id: string){
return this.http.get(`${this.API}/unit/${id}`);
}
getStructures(){
return this.http.get(`${this.API}/structures`);
}
getStructure(id: string){
return this.http.get(`${this.API}/structure/${id}`);
}
getTechnologies(){
return this.http.get(`${this.API}/technologies`);
}
getTechnology(id: string){
return this.http.get(`${this.API}/technology/${id}`);
}
}
答案 0 :(得分:1)
这是由same origin policy引起的问题。您可以使用代理配置在开发模式下绕过此操作。
您的服务
API = 'api/v1';
proxy.conf.json
{
"/api/v1": {
"target": "https://age-of-empires-2-api.herokuapp.com",
"secure": false,
"changeOrigin": true
}
}
这会将/api/v1/stuctures
的任何请求代理到https://age-of-empires-2-api.herokuapp.com/api/v1/stuctures
。
要使用代理,请运行ng serve --proxy-config proxy.conf.json
详细了解如何使用proxy
请注意,这仅适用于开发模式