我正在尝试使用HttpClient模块从教程中调用简单的API,但是在控制台中却收到“ HttpErrorResponse:未知错误”。
我在这里打电话:
this.http.get('https://api.github.com/users/seeschweiler').subscribe(data => {
console.log(data);
});
}
答案 0 :(得分:0)
对我来说很好,请参阅stackblitz.com。
打字稿组件
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
template: `<div *ngIf="githubData">Id = {{githubData.id}}</div>`,
})
export class AppComponent implements OnInit {
githubData: any;
constructor(private http: HttpClient){}
ngOnInit(){
this.http.get('https://api.github.com/users/seeschweiler').subscribe(data => {
this.githubData = data;
});
}
}
答案 1 :(得分:0)
看看错误是什么然后从那里调试。
this.http.get('https://api.github.com/users/seeschweiler').subscribe(data => {
console.log(data);
},
error => {
console.log('Log the error here: ', error);
});
}
答案 2 :(得分:0)
以下代码对我有用:- 1)在component.ts
GetData() {
this.myService.GetUsers(this.someId).subscribe(
success => {
},
errors => {
}
);
2)在service.ts
GetUsers(someId: number) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let params: URLSearchParams = new URLSearchParams();
params.set('someId', someId.toString());
let options = new RequestOptions({ headers: headers, search: params });
return this.http.get('https://api.xyz.com/users/GetUsersList', options)
.map(res => res.json());
}
}
3)不要忘记从rxjs / operator导入“ .map”。