简体   繁体   中英

Angular subscribe function with HTTP Get never returning

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.

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 }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM