如何从HttpClient获取json文件? [英] How to get json file from HttpClient?
问题描述
我正在尝试从HttpClient
获取json
文件,但是添加.subscribe
I am trying to get a json
file from HttpClient
, but I get a error when I add .subscribe
进口:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
import { HttpModule, Request, Response, Headers, Http } from '@angular/http';
import { Observable } from 'rxjs';
我的代码:
当我添加.subscribe
(图像中标记为黄色)时,出现以下错误.是什么意思?
When I add .subscribe
(yellow marked in image) I got the following error. What does it mean?
对象{_body:错误,状态:0,确定:false,statusText:",标头: 对象,类型:3,网址:null}
Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }
推荐答案
如果您想使事情变得非常清晰和井井有条,则应创建一个angular服务并从组件中调用该服务.
If you want to make something very clear and organised you should create a service in angular and call the service from your component.
例如:
Service.ts:
import { Injectable } from "@angular/core";
import { Observable, throwError } from "rxjs";
import {
HttpClient,
HttpHeaders,
HttpErrorResponse
} from "@angular/common/http";
import { catchError, map } from "rxjs/operators";
// Set the http options
const httpOptions = {
headers: new HttpHeaders({ "Content-Type": "application/json", "Authorization": "c31z" })
};
@Injectable({
providedIn: "root"
/**
* Service to call all the API
*/
export class ApiService {
constructor(private http: HttpClient) {}
/**
* Function to handle error when the server return an error
*
* @param error
*/
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error("An error occurred:", error.error.message);
} else {
// The backend returned an unsuccessful response code. The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.error}`
);
}
// return an observable with a user-facing error message
return throwError(error);
}
/**
* Function to extract the data when the server return some
*
* @param res
*/
private extractData(res: Response) {
let body = res;
return body || {};
}
/**
* Function to GET what you want
*
* @param url
*/
public getListOfGroup(url: string): Observable<any> {
// Call the http GET
return this.http.get(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError)
);
}
}
Component.ts:
import { Component, OnInit } from "@angular/core";
import { ApiService } from "../../services/api.service";
@Component({
selector: "app-example",
templateUrl: "./example.component.html",
styleUrls: ["./example.component.css"]
})
export class ExampleComponent implements OnInit{
url = "/url/path/to/your/server";
constructor(private api: ApiService) {}
ngOnInit() {
this.api
.getListOfGroup(url)
.subscribe(
data => {
console.log(data);
},
err => {
console.log(err);
}
);
}
}
我的建议是跟随有角度的人开始学习,否则你会很快迷路. 角度服务教程
My advice would be to follow the getting start of angular if not you will be quickly lost. Service tutorial angular
这篇关于如何从HttpClient获取json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!