2

I got a problem with understanding how HttpClient works

api.service.js

import {Injectable} from '@angular/core';
import {environment} from '../../environments/environment';
import {HttpClient} from '@angular/common/http';
import {Task} from './task';
import 'rxjs/add/operator/map';

const API_URL = environment.apiUrl;

interface JSONObject {
  _id: string;
  title: string;
  created_at: string;
  startTime: string;
  endTime: string;
  state: boolean;
  description: string;
}

@Injectable()
export class ApiService {
  public tasks;

  constructor(private http: HttpClient) {
  }

  public getAllTasks() {
    return this.http
      .get<JSONObject>(API_URL + '/api/task').subscribe(
        data => {
          this.tasks = data;
          console.log(data); //Returning Array
        });
  }
}

task.component.ts

import {Component, OnInit} from '@angular/core';
import {ApiService} from './api.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  styleUrls: ['./task.component.css'],
  providers: [ApiService]
})
export class TaskComponent implements OnInit {

  constructor(private apiService: ApiService) {

  }

  ngOnInit() {
    console.log(this.apiService.tasks); // <<< Not Returning JSON :(
  }

  getAllTasks() {
    return this.apiService.getAllTasks();
  }
}

I am new to Angular 5 and have to create a CRUD App for lesson but actually stuck in at this problem.

How can I get the JSON Object in task.component.ts ?

1
  • did the answer help Commented Nov 6, 2017 at 16:51

1 Answer 1

4

Don't subscribe to the observable in the service and do not store the value inside it. Change the method to:

public getAllTasks() {
  return this.http.get<JSONObject>(API_URL + '/api/task')
}

so your service is specific to handle the API requests. Then in your component:

ngOnInit() {
  this.apiService.getAllTasks()
  .subscribe( data => {
    //now you have the data
  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This works like a charm. So it is best practice to not store data in services? I have much to learn in angular..
You can store them in a service, but then the best approach IMO is to use EventEmitter (angular.io/api/core/EventEmitter) to "broadcast" to subscribed listeners (in components) that a value has been changed. Basically, the components subscribe to observables that emits values when the service has values changed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.