1

So I have setup this service to console log the response from a News API like so:

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

@Injectable({
  providedIn: 'root'
})
export class NewsApiService {
  private url = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getArticles() {
    this.http.get(this.url).subscribe(response => {
      console.log(response);
    });
  }
}

This is something temporary I would like to do until I get up to speed with RxJS Observables, but I am getting nothing in the console and absolutely no error anywhere.

Daniel
  • 14,004
  • 16
  • 96
  • 156

1 Answers1

0

That is because inside your NewsApiService > getArticles you are subscribing to the call from you HTTP request instead of returning the result.

Attached herewith is the Stackblitz Demo for your reference. You can check the console tab


Your NewsApiService should be like this:

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

import { Observable } from "rxjs";

@Injectable({ providedIn: "root" })
export class NewsApiService {
  private url = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: HttpClient) {}

  getArticles(): Observable<any> {                  // Add the return type to be Observable 
                                                    // and you can change the <any> to your own type
    return this.http.get(this.url);
  }
}

Component

@Component({...})
export class AppComponent implements OnInit {

  constructor(private newsService: NewsApiService) {}

  ngOnInit(): void {
    this.newsService
      .getArticles()
      .subscribe(res => console.log(res));         // Log the result from service

  }
}
KShewengger
  • 7,853
  • 3
  • 24
  • 36
  • 1
    okay so there is no getting around having to access an `Observable` from **rxjs**. Thank you. – Daniel Nov 04 '20 at 05:38