我想在 Angular 8 中快速控制台记录此 API 的响应
I would like to quickly console log the response from this API in Angular 8
所以我设置了这个 服务 来控制台记录来自新闻 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
}
}
所以我设置了这个 服务 来控制台记录来自新闻 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
}
}