我想在Angular 8中快速控制台记录此API的响应

问题描述

因此,我已经设置了此服务,以控制台方式记录来自News API的响应,如下所示:

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);
    });
  }
}

这是我暂时想做的事情,直到我开始熟悉RxJS Observables为止,但是在控制台中什么也没得到,在任何地方都没有错误

解决方法

这是因为在NewsApiService > getArticles中,您正在订阅HTTP请求中的调用,而不是返回结果。

随信附上 Stackblitz Demo 供您参考。您可以选中 console 标签


您的 NewsApiService 应该是这样的:

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({...})
export class AppComponent implements OnInit {

  constructor(private newsService: NewsApiService) {}

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

  }
}