【发布时间】:2020-07-16 16:18:01
【问题描述】:
我是 Angular 的新手,但我仍然不太了解它是如何工作的。 我从我构建的 API 中获取数据。它有效,因为我在邮递员中对其进行了测试。 我无法在我的 Angular 应用程序中显示它们,我不明白为什么。
我的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>
谁能解释为什么我仍然无法显示我的图书数据?
【问题讨论】:
-
您在浏览器开发者工具中看到了什么?在网络选项卡上发出请求了吗? console.log 在控制台打印一些东西?
-
可能是 cors 问题。看看浏览器的调试工具
-
控制台:“跨域请求被阻止:同源策略不允许读取localhost:8080/returnShelf的远程资源。(原因:CORS请求未成功)”
-
我不知道该怎么做
-
你能试试这个 public get() { return this.httpClient.jsonp(this.SERVER_URL); } ...... insted of public get() { return this.httpClient.get(this.SERVER_URL); }
标签: angular typescript components angular8 ngfor