Как получить файл JSON из HttpClient? - PullRequest
0 голосов
/ 28 августа 2018

Я пытаюсь получить файл json из HttpClient, но при добавлении .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';

Мой код:

enter image description here

Когда я добавляю .subscribe (отмечено желтым цветом на изображении), я получил следующую ошибку. Что это значит?

Object {_body: error, status: 0, ok: false, statusText: "", заголовки: Объект, тип: 3, URL: ноль}

1 Ответ

0 голосов
/ 28 августа 2018

Если вы хотите сделать что-то очень четкое и организованное, вы должны создать службу на английском языке и вызвать службу из вашего компонента.

Как например:

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

}

Я бы посоветовал последовать началу углового, если нет, вы быстро потеряетесь. Сервисный учебник угловой

...