You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5如何拦截SpringBoot转发至localhost的POST JSON数据?

Hey there! Let's fix this up for you. Right now your code is set up to send data to an API, but what you need is to receive and display the JSON data that your Spring Boot API forwards to localhost. Here are two common approaches to make this work:

Option 1: Poll for Data (Simple, No Real-Time)

If you don't need instant updates, you can have your Spring Boot app store the received JSON and let your Angular frontend periodically fetch it.

Step 1: Update Your Spring Boot Controller

First, modify your Spring Boot endpoint to save the incoming JSON and expose a GET endpoint for your frontend:

@RestController
public class ForwardController {
    // Use a cache/database in production instead of in-memory storage
    private String latestForwardedJson;

    // Accept incoming POST requests from external sources
    @PostMapping("/receive-external-data")
    public ResponseEntity<String> receiveExternalData(@RequestBody String jsonPayload) {
        this.latestForwardedJson = jsonPayload;
        return ResponseEntity.ok("Data received and stored");
    }

    // Expose data to your Angular frontend
    @GetMapping("/get-forwarded-data")
    public ResponseEntity<String> getForwardedData() {
        return ResponseEntity.ok(latestForwardedJson);
    }
}

Step 2: Update Angular Service

Replace your existing MyDataService with one that fetches the forwarded data:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MyDataService {
  constructor(private http: HttpClient) { }

  getForwardedData(): Observable<any> {
    // Replace with your Spring Boot app's URL
    return this.http.get("http://localhost:8080/get-forwarded-data")
      .pipe(
        catchError(err => Observable.throw(err))
      );
  }
}

Step 3: Update Angular Component

Modify your component to fetch and display the data (we'll add polling to check for updates):

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MyDataService } from './my-data.service';

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

  constructor(private route: ActivatedRoute, private dataService: MyDataService ) { 
    console.log(window.location.href); 
  }

  ngOnInit() {
    // Check for new data every 3 seconds (adjust interval as needed)
    setInterval(() => {
      this.dataService.getForwardedData()
        .subscribe(
          res => {
            this.forwardedJson = res;
            console.log("Received forwarded JSON:", res);
          },
          err => alert("Failed to load forwarded data")
        );
    }, 3000);
  }
}

Step 4: Display Data in Template

Add this to your component's HTML to show the JSON:

<h3>Forwarded JSON Data:</h3>
<pre>{{ forwardedJson | json }}</pre>

Option 2: Real-Time WebSocket (Instant Updates)

If you need to see the data as soon as it's forwarded, use WebSockets for real-time push.

Step 1: Configure Spring Boot WebSocket

Add WebSocket support to your Spring Boot app:

// WebSocket Configuration
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new ForwardWebSocketHandler(), "/forward-ws")
                .setAllowedOrigins("*"); // Allow your Angular app's origin
    }
}

// WebSocket Handler to push data to frontend
public class ForwardWebSocketHandler extends TextWebSocketHandler {
    private static final List<WebSocketSession> activeSessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        activeSessions.add(session);
    }

    // Static method to send data to all connected clients
    public static void sendForwardedData(String json) throws IOException {
        for (WebSocketSession session : activeSessions) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(json));
            }
        }
    }
}

// Update your Controller to push data via WebSocket
@RestController
public class ForwardController {
    @PostMapping("/receive-external-data")
    public ResponseEntity<String> receiveExternalData(@RequestBody String jsonPayload) throws IOException {
        // Push the received data to all connected Angular clients
        ForwardWebSocketHandler.sendForwardedData(jsonPayload);
        return ResponseEntity.ok("Data received and forwarded in real-time");
    }
}

Step 2: Update Angular Service for WebSocket

Create a service to handle WebSocket connections:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MyDataService {
  private socket: WebSocket;

  constructor() { }

  connectToWebSocket(): Observable<any> {
    this.socket = new WebSocket('ws://localhost:8080/forward-ws');

    return new Observable(observer => {
      // Listen for incoming messages
      this.socket.onmessage = (event) => {
        observer.next(JSON.parse(event.data));
      };

      // Handle errors
      this.socket.onerror = (error) => {
        observer.error(error);
      };

      // Clean up on close
      this.socket.onclose = () => {
        observer.complete();
      };
    });
  }
}

Step 3: Update Angular Component

Modify your component to listen for real-time updates:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MyDataService } from './my-data.service';

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

  constructor(private route: ActivatedRoute, private dataService: MyDataService ) { 
    console.log(window.location.href); 
  }

  ngOnInit() {
    this.dataService.connectToWebSocket()
      .subscribe(
        res => {
          this.forwardedJson = res;
          console.log("Real-time forwarded JSON:", res);
        },
        err => alert("WebSocket connection failed")
      );
  }
}

Step 4: Display Data (Same as Option 1)

Use the same HTML template as before to render the JSON.


内容的提问来源于stack exchange,提问作者Snk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:20:56