【问题标题】:How to get json file from HttpClient?如何从 HttpClient 获取 json 文件?
【发布时间】:2018-08-28 11:42:07
【问题描述】:

我正在尝试从HttpClient 获取json 文件,但添加.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(图像中标记为黄色)时,出现以下错误。什么意思?

Object { _body:错误,状态:0,ok:false,statusText:“”,标题: 对象,类型:3,url:null }

【问题讨论】:

    标签: json angular authentication httpclient response


    【解决方案1】:

    如果你想让一些事情变得非常清晰和有条理,你应该在 Angular 中创建一个服务并从你的组件中调用该服务。

    例如这样:

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

    我的建议是跟随 Angular 的入门,否则你很快就会迷失方向。 Service tutorial angular

    【讨论】:

    • 感谢它帮了大忙!对不起,如果我的问题不是很清楚!
    • 虽然这对新开发人员很有帮助,但目前并不能回答所提出的问题。
    猜你喜欢
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多