Home > Software engineering >  Angular subscribe function with HTTP Get never returning
Angular subscribe function with HTTP Get never returning

Time:08-16

This Component calls the service.

  req: Observable<Object> = this.blogEntryService.testFunction();

  constructor(private blogEntryService: BlogEntryService) {
  }

  ngOnInit(): void {
    console.log("Init page");
    this.req.subscribe((res: any) => {
      console.log(res)
    });
  }

Then the service returns the observable:

  testFunction() {
    console.log("Testing connection")
    return this.http.get('https://jsonplaceholder.typicode.com/todos/1');
  }

When executing there are only 2 logs:

  • Testing connection
  • Init page

There is no result logged

I have inspected the app with AngularDevTools and checked the observable is created, it is.

Any idea of what could be the issue? No error is ever logged.

Note: This exact code works with InMemoryDatabase while testing.

CodePudding user response:

Tested this code, works as expected

app.component.ts

import { Component, OnInit } from "@angular/core";
import { BlogEntryService } from './blog-entry.service';

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  constructor(private blogEntryService: BlogEntryService) {

  }

  ngOnInit(): void {
    this.blogEntryService.testFunction().subscribe({ next: response => {console.log(response);}});
  }
}

blog-entry.service.ts

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

@Injectable({ providedIn: 'root' })
export class BlogEntryService {
  constructor(private http: HttpClient) {}

  testFunction(): Observable<any> {
    return this.http
      .get('https://jsonplaceholder.typicode.com/todos/1');
  }
}

In your app.module.ts add HttpClientModule to imports array as this

imports: [BrowserModule, HttpClientModule]

Outputs user { userId: 1, id: 1, title: "delectus aut autem", completed: false }

CodePudding user response:

For some reason import { HttpClientTestingModule } from '@angular/common/http/testing' blocks all http requests. My solution was removing it for the time being

  • Related