Angular 8 / Spring Boot / API-вызовы Rest / Отображение данных - PullRequest
0 голосов
/ 05 февраля 2020

Я пишу простой клиент отдыха с использованием модуля Angular 8 HttpClient и пружинных загрузок rest RestController Framework.

Я написал службу в angular и вот она:

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


@Injectable({
  providedIn: 'root'
})
export class GetTicketService {

  constructor(private http:HttpClient) { }

  ticket: any;
  url1: any = "http://localhost:8085/post";
  testurl: any = "http://localhost:8085/greeting";


  public getTest() {
    console.log("in method freeAPIService");
    //const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    return this.http.get(this.testurl);
  }



  public getTicket() {
    console.log("creating headers");
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    console.log("Making a url call to: " + this.url1);
    console.log("the call: this.http.post(this.url,headers)" + this.url1 + headers);


    return this.http.post(this.url1,headers);
  }



}

Мой класс отдыха при весенней загрузке выглядит следующим образом:

package cors.terida.com.teridacors;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

@RestController
public class corsEndPoint {
    @CrossOrigin(origins="http://localhost:4200")
    @RequestMapping(value="/greeting")
    public String sayGreeting() {
        return "Hello Chris";

    }

    @RequestMapping(value = "/post", produces = MediaType.APPLICATION_JSON_VALUE, method= RequestMethod.POST)
    //@CrossOrigin(origins="http://localhost:4200")
    @CrossOrigin()
    public String getTicketFromPost() {
        final String URL = "http://15.222.0.10/trusted";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept((Arrays.asList(MediaType.APPLICATION_JSON)));
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("username", "admin");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,headers);
        return restTemplate.exchange(URL, HttpMethod.POST,request,String.class).getBody();

    }


}

Мой компонент использует сервис для получения точек отдыха. как это:

import { Component, OnInit } from '@angular/core';
import { GetTicketService } from './../get-ticket.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-displayticket',
  templateUrl: './displayticket.component.html',
  styleUrls: ['./displayticket.component.css']
})
export class DisplayticketComponent implements OnInit {
  ticket: any;
  greeting: any;
  message: any = "This is a test";
  response: any;
 // constructor(private service:GetTicketService) { }

 constructor (private service:GetTicketService) { }

  ngOnInit() {
    this.greeting = this.service.getTest();
    this.greeting.subscribe((data)=> console.log(data));

    this.ticket = this.service.getTicket();
    this.ticket.subscribe((ticket) => console.log(ticket));


  }

}

и мой компонент. html файл записи отображает данные примерно так:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    {{message}}
    {{greeting}}
    {{ticket}}
</body>
</html>

Внутри веб-браузера, когда я загружаю страницу, переходя на localhost : 4200 Я получаю два [[объекта]], где я ожидаю, что строка будет. Каждая конечная точка отображает только одну строку, а не список json объектов, поэтому я не думаю, что мне нужно l oop просматривать их.

Может кто-нибудь помочь мне разобраться?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...