简体   繁体   English

Angular 订阅 function 与 HTTP 获得永不返回

[英]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:然后服务返回 observable:

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

When executing there are only 2 logs:执行时只有 2 个日志:

  • Testing connection测试连接
  • Init page初始化页面

There is no result logged没有记录结果

I have inspected the app with AngularDevTools and checked the observable is created, it is.我已经使用 AngularDevTools 检查了应用程序并检查了 observable 是否已创建。

Any idea of what could be the issue?知道可能是什么问题吗? No error is ever logged.从未记录任何错误。

Note: This exact code works with InMemoryDatabase while testing.注意:这个确切的代码在测试时适用于 InMemoryDatabase。

Tested this code, works as expected测试此代码,按预期工作

app.component.ts 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 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在您的app.module.ts 中,将 HttpClientModule 添加到导入数组中,如下所示

imports: [BrowserModule, HttpClientModule]导入:[BrowserModule, HttpClientModule]

Outputs user { userId: 1, id: 1, title: "delectus aut autem", completed: false }输出 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.由于某种原因import { HttpClientTestingModule } from '@angular/common/http/testing'阻止所有 http 请求。 My solution was removing it for the time being我的解决方案是暂时删除它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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