[英]Angular http get request do nothing
所以,我正在嘗試向 API 發出請求(例如 SWAPI API)
在我的 app.module 中:
...
...
import { HttpClientModule } from '@angular/common/http';
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientTestingModule,
HttpClientModule,
...
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
在我的組件中,我這樣做:
ngOnInit(): void {
this.studyService.getSWAPI_List().subscribe(response => {
console.log(response)
}, error => {console.log(error)});
this.studyService.getSWAPI_List2().subscribe(response => {
console.log(response)
}, error => {console.log(error)});
}
在我的服務中:
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor(private http: HttpClient) { }
getSWAPI_List(){
console.log('Request SWAPI list')
return this.http.get('https://swapi.dev/api/people/', options);
}
getSWAPI_List2(){
console.log('Request SWAPI list2')
return this.http.get('https://swapi.dev/api/people/');
}
}
在我的瀏覽器控制台中,我看不到任何響應(對於帶有和不帶有標頭的請求),但是如果我在瀏覽器中使用這個簡單的 URL 一切正常...
我在控制台(以及控制台的網絡選項卡中)也沒有錯誤......
有人可以幫我看看為什么嗎?
乍一看,代碼似乎是正確的。
我的Stackblitz 示例也按預期工作。
控制台 output:
Request SWAPI list
Request SWAPI list2
Angular is running in development mode. Call enableProdMode() to enable production mode.
{count: 82, next: "http://swapi.dev/api/people/?page=2", previous: null, results: Array[10]…}
{count: 82, next: "http://swapi.dev/api/people/?page=2", previous: null, results: Array[10]…}
我建議您發布更多信息或更新 Stackblitz 示例,以找到您的真正問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.