Search code examples
angular-servicesangular8angular-http

Angular8 http and services missunderstand


I'm here because I do not understand how Http works in angular. I would create a "news" thread on my website. To do that I have created a service in my angular app that calls a .net core web API. Also, I would add a paginate to my thread (I want to display news by 5 on the page). I can get my values, that is not my issue here. But, to create my paginate, I need to have values for number of pages calculation.

I tried to add code to create my paginate (number of pages, number of elements...) but I always get 0 to these values and my array of news is filled after the onInit(). This is what I don't understand.

This is my component:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { NewsService } from '../news.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  title = 'News';
  news = [];
  displayed = [];
  numberOfPages = 0;

  constructor(private newsService: NewsService) { }

  ngOnInit() {
    // I don't really understand these lines (mainly the subscribe part)
    this.newsService.getAllNews().subscribe((data) => {
      this.news = Array.from(Object.keys(data), k => data[k]);
      // this console.log appears after the onInit(), why ?
      console.log(this.news);
    });

    this.numberOfPages = this.news.length / 5; // Get 0 here, why ?
  }

}

My service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class NewsService {
  private finalData = [];
  private apiUrl = 'https://localhost:5001/api/v1/posts';

  constructor(private http: HttpClient) { }

  getAllNews() {
    return this.http.get(this.apiUrl);
  }
}

In the browser console, I get this: console screen

Maybe I forgot something in my code or I don't know what.

Someone can help me to achieve my goal? I want to understand how to proceed to make a working paginate for my news.


Solution

  • You should add

    this.numberOfPages = this.news.length / 5;
    

    inside the subscribe

    this.newsService.getAllNews().subscribe((data) => {
          this.news = Array.from(Object.keys(data), k => data[k]);
          // this console.log appears after the onInit(), why ?
          console.log(this.news);
        });
    

    like so:

    this.newsService.getAllNews().subscribe((data) => {
          this.news = Array.from(Object.keys(data), k => data[k]);
          // this console.log appears after the onInit(), why ?
          console.log(this.news);
          this.numberOfPages = this.news.length / 5;
        });
    

    My guess is that when you try to initialise the this.numberOfPagesthe this.news.length is not yet set(data are not yet retrieved from the API). Hope this helps