lundi 18 février 2019

Problem with consuming a laravel 5.7 API in Angular7

I'm trying to make my own API in laravel 5.7 and consume it in Angular7.

I tried an API from JsonPlaceholder and everything went well. I got problems when i'm trying to consume a self-made API in Laravel. I tried to make a function in a controller that return a json_encode($array).After this, i tested it in Postman and everything went as expectat.

The json has dummy data, but this dosn't matter.

When i called it from Angular, i got this error in console:

error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … } ​ headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) } ​ message: "Http failure response for http://127.0.0.1:8000/api/test: 0 Unknown Error" ​ name: "HttpErrorResponse" ​ ok: false ​ status: 0 ​ statusText: "Unknown Error" ​ url: "http://127.0.0.1:8000/api/test"

After that, i tried to use a collection in Laravel.The Postman response was ok, but the angular response is the same.

Method Way:

public function test() {
        $test = [
            'name' => 'Andi',
            'password' => 'Parola'
        ];

        return response()->json($test);
}

Collection Way:

public function test() {
        $test = [
            'name' => 'Andi',
            'password' => 'Parola'
        ];

        return new ApiTest($test);
}

Angular Service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class SteamCallsService {

  configUrl = 'http://127.0.0.1:8000/api/test';

  constructor(
    private http: HttpClient
  ) { }

  async newFunction():Promise<any> {
    try {
      const item = await this.http.get(this.configUrl).toPromise();
      return item;

    } catch (error) {
      console.error(error);
    }
  }
}

Angular component

import { Component, OnInit } from '@angular/core';

//Services
import {  SteamCallsService } from '../app/steam-calls.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  array = [];


  constructor (
    private _steamApi: SteamCallsService
  ) {}

  ngOnInit() {
    this.getJson();
  }

  async getJson() {
    const res = await this._steamApi.newFunction();

    this.array = res;  
  }
}


I expect a simple json as response. Edit: In network tab(from inspector) the status of the request is 200 and the data is exactly what i was expecting. Why do i get this error and how can i use that data?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire