[英]Angular http get does nothing
I'm following tutorial on Udemy and I can't workout how to use HTTP GET in Angular.我正在关注 Udemy 上的教程,但无法锻炼如何在 Angular 中使用 HTTP GET。 I've created component called posts, here is code of posts.component.ts:
我创建了名为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() {
}
}
And there is posts.component.html还有posts.component.html
<ul class="list-group">
<li
*ngFor="let post of posts"
class="list-group-item">
{{post.title}}
</li>
</ul>
I've also imported HttpModule in app.module.ts, but i cannot se any resoults, my site on localhost:4200 is the same as it was before I've added "posts".我还在 app.module.ts 中导入了 HttpModule,但我无法看到任何结果,我在 localhost:4200 上的站点与添加“帖子”之前的站点相同。 Also there isn't any error while I'm compiling or in web browser console.
在我编译时或在 web 浏览器控制台中也没有任何错误。 This is what is in my web browser console:
这是我的 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
Do not use the old module for http requests:不要将旧模块用于 http 请求:
import { Http } from '@angular/http';
Use the new module instead:请改用新模块:
import { HttpClient } from '@angular/common/http';
Here an example: https://stackblitz.com/edit/angular-http-client-first-example?file=src/app/app.component.ts这里是一个例子: https://stackblitz.com/edit/angular-http-client-first-example?file=src/app/app.component.ts
Edit: Use this version:编辑:使用这个版本:
constructor(
private readonly _http: HttpClient) {
this.getPosts().subscribe(res => {
this.posts = res;
});
}
getPosts(): Observable<any[]> {
console.log('getPosts');
return this._http.get('https://jsonplaceholder.typicode.com/todos').pipe(
map<any, any[]>(response => {
console.log(response);
return response;
})
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.