0

I'm retrieving data from a json server using an service, but, when, inside the service i make a console.log() the console shows me the data retrieved from the json, but when I try to make it out of the service I get the errors below:

enter image description here

load-home.service

import { Injectable } from '@angular/core';

import { API } from '../../app.api'

import { HttpClient } from '@angular/common/http'

@Injectable()

export class LoadHomeService {

  constructor(private http: HttpClient) { 

  }

  getTarefasInternas(): any {
    return this.http.get(`${API}/getTarefasInternas`)
      .subscribe((response) =>{
        console.log (response) // it works
      } 
  )}

  getTarefasExternas(): any {
    return this.http.get(`${API}/home`)
      .subscribe((response) =>{}
  )}
}

home.page.ts

import { Component } from '@angular/core';
import { LoadHomeService } from './load-home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage  {
  tarefasInternas : any
  constructor(private homeService: LoadHomeService) { }

  ngOnInit() {
    this.tarefasInternas = this.homeService.getTarefasInternas()

  }
}

Html markup:

<ion-list>
    <ion-item *ngFor="let tarefa of tarefasInternas" class="in-list item ion-focusable item-label hydrated">
      <ion-label class="sc-ion-label-ios-h sc-ion-label-ios-s hydrated">
        <h2>{{tarefa.descricao}}</h2>
        <h3>{{tarefa.inicio}} - {{tarefa.fim}}</h3>
        <p>{{tarefa.comentario}}</p>
      </ion-label>
    </ion-item>
  </ion-list>

When I call the console.log out of the service: enter image description here

Tiago Silveira
  • 267
  • 4
  • 14

1 Answers1

2

Change your service method just as below and subscribe in your component,

getTarefasInternas(): any {
    return this.http.get(`${API}/getTarefasInternas`)
)}

and in component

ngOnInit() {
this.homeService.getTarefasInternas().subscribe((data)=>{
    this.tarefasInternas = data;
});
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thanks, It Works! But when and how should I Unsubscribe from this service? using the pipe async solves this? – Tiago Silveira Mar 05 '19 at 02:16
  • you can still do it in the component itself – Sajeetharan Mar 05 '19 at 02:17
  • Sorry, but I don't understand. When I Change page, for example, the unsubscription is made? I want to prevent memoleaks – Tiago Silveira Mar 05 '19 at 02:18
  • You don't need to unsubscribe from HttpClient observables: https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods – Kris Mar 05 '19 at 04:23