简体   繁体   中英

Angular http get does nothing

I'm following tutorial on Udemy and I can't workout how to use HTTP GET in Angular. I've created component called posts, here is code of 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

<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". Also there isn't any error while I'm compiling or in web browser console. This is what is in my web browser console:

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:

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

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;
          })
      );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM