简体   繁体   中英

Consuming a REST API angular 8

I have a rest API at: https://back-end-gubee.herokuapp.com/service It returns me three objects, these have attributes and two object lists internally.

[{"id":20,"name":"Gubee Fretes","description":"Ferramenta para gestão e calculo de fretes","active":false,"value":0.0,"targets":[{"id":1,"name":"Ecommerce","description":null},{"id":2,"name":"ERP","description":null},{"id":3,"name":"Loja fisica","description":null}],"technologies":[{"id":10,"name":"MongoDB","description":null,"developer":null,"version":null},{"id":9,"name":"NodeJS","description":null,"developer":null,"version":null}]},{"id":21,"name":"Gubee Integrador","description":"Ferramenta de integração para marketplaces","active":false,"value":0.0,"targets":[{"id":4,"name":"Lojista que não desejam possuir ecommerce","description":null},{"id":1,"name":"Ecommerce","description":null},{"id":2,"name":"ERP","description":null}],"technologies":[{"id":10,"name":"MongoDB","description":null,"developer":null,"version":null},{"id":14,"name":"Event Stream","description":null,"developer":null,"version":null},{"id":11,"name":"Java 10","description":null,"developer":null,"version":null},{"id":12,"name":"Kotlin","description":null,"developer":null,"version":null},{"id":13,"name":"Kafka","description":null,"developer":null,"version":null},{"id":15,"name":"Redis","description":null,"developer":null,"version":null}]},{"id":22,"name":"Gubee AntiFraude","description":"Ferramenta especialistas em detecção e prevenção à fraude","active":false,"value":0.0,"targets":[{"id":1,"name":"Ecommerce","description":null},{"id":6,"name":"Venda direta","description":null},{"id":7,"name":"Mobile First","description":null},{"id":5,"name":"Telecom","description":null},{"id":8,"name":"Digital Onboarding","description":null}],"technologies":[{"id":17,"name":"Hadoop","description":null,"developer":null,"version":null},{"id":16,"name":"Big Data Analytics","description":null,"developer":null,"version":null},{"id":19,"name":"Cassandra","description":null,"developer":null,"version":null},{"id":18,"name":"Pig","description":null,"developer":null,"version":null},{"id":13,"name":"Kafka","description":null,"developer":null,"version":null}]}]

I am trying to consume this JSON with the angular but every time throws the following error:

{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null,
    "headers": {}
  },
  "status": 0,
  "statusText": "Unknown Error",
  "url": "https://back-end-gubee.herokuapp.com/service/products",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for https://back-end-gubee.herokuapp.com/service/products: 0 Unknown Error",
  "error": {
    "isTrusted": true
  }
}

Which is odd because the request is successfully performed by the get method.

This is the response of the request made by the angular.

Request URL:https://back-end-gubee.herokuapp.com/service
Request Method:GET
Remote Address:3.225.95.126:443
Status Code:
200
Version:HTTP/1.1
Referrer Policy:no-referrer-when-downgrade

This is my code:

SERVICE

import { Products } from './../../models/Product.models';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class ProductService {


  constructor(private http: HttpClient) { }

  public getProducts(): Observable<Products[]> {
    return this.http.get<Products[]>(
      'https://back-end-gubee.herokuapp.com/service');
    }
}

COMPONENT

import { Products } from './../../models/Product.models';
import { ProductService } from './../../services/productService/product.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-component',
  templateUrl: './product-component.component.html',
  styleUrls: ['./product-component.component.css']
})
export class ProductComponentComponent implements OnInit {

  products: Products[];
  MyError: any;

  constructor(private productService: ProductService) {
    this.getter();
   }

  ngOnInit() {
  }

 getter() {
    this.productService.getProducts().subscribe(
      (data: Products[]) => {
        this.products = data;
        console.log(data);
    },
    (error) => {
      this.MyError = error;
    });
  }
}

My model

import { Technology } from './Technology.models';
import { Target } from './Target.models';

export class Products {
 public id: number;
 public name: string;
 public description: string;
 public valuel: number;
 public active: boolean;
 public targets: Target[];
 public technologies: Technology[];
}

My endPoint

@Service
@RestController
public class ProductPresentation implements CRUDController<Product> {

    @Autowired
    private ProductService productService;

    @GetMapping("/service")
    @Override
    public ResponseEntity<List<Product>> readAll() {
        return ResponseEntity.ok(productService.readAll());
    }
}

My Entity

@Getter
@Setter
@Entity
public class Product extends Person implements Serializable {

    private boolean active;
    private double value;

    @SerializedName("targets")
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Target> targets;

    @SerializedName("technologies")
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Technology> technologies;

    @Builder
    public static Product creat (boolean active, double value, Set<Target> targets, Set<Technology> technologies, String name, String description) {
        Product product =new Product();
        product.setName(name);
        product.setDescription(description);
        product.setActive(active);
        product.setValue(value);
        product.setTargets(targets);
        product.setTechnologies(technologies);

        return product;
    }
}

I am using spring-boot on the back and angular 8 on the front. Need help I'm stopped. Thank you.

I don't see nothing wrong besides the CORS error, which is caused by the Access-Control-Allow-Origin not being present on the header. You can pass such options on the http.get(url, options) options parameter.

As your Angular application is making the request from a different domain, you should enable CORS for your Spring Boot controller like:

@Service @RestController 
public class ProductPresentation implements CRUDController<Product> {

    @Autowired
    private ProductService productService;

    @CrossOrigin(origins= "*") // or be more specific e.g. http://localhost:4200
    @GetMapping("/service")
    @Override
    public ResponseEntity<List<Product>> readAll() {
        return ResponseEntity.ok(productService.readAll());
    } 
}

Read further information on CORS with Spring Boot on one of their guides .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM