【发布时间】:2020-08-18 03:10:05
【问题描述】:
我正在关注 Udemy 上的教程,但我无法练习如何在 Angular 中使用 HTTP GET。我已经创建了名为 posts 的组件,这里是 posts.component.ts 的代码:
import { Http } from '@angular/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
posts: any[];
constructor(http: Http) {
http.get('http://jsonplaceholder.typicode.com/posts')
.subscribe( response => {
this.posts = response.json();
});
}
ngOnInit() {
}
}
还有posts.component.html
<ul class="list-group">
<li
*ngFor="let post of posts"
class="list-group-item">
{{post.title}}
</li>
</ul>
我还在 app.module.ts 中导入了 HttpModule,但我无法看到任何结果,我在 localhost:4200 上的站点与添加“帖子”之前的站点相同。在我编译或在 Web 浏览器控制台中也没有任何错误。这是我的网络浏览器控制台中的内容:
DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.preload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
【问题讨论】:
-
这是一个非常古老的 Angular 版本。您最好花时间阅读 angular.io 上的官方文档和指南。您的代码也没有什么特别的问题。它应该像你展示的那样工作,所以你的结果有一些缺失的信息。您应该确定请求是否真的发出,如果是,
response.json()是否返回您期望的结果。
标签: angular http get angular-httpclient