我正在構建一個連接到我的 java 后端(restapi)的角度專案。專案基礎已經完成,但現在我正在一一添加一些高級呼叫。突然,我到了要實作一個新方法的地步,但是請求并沒有到達控制器中的方法。我什至在前端沒有收到錯誤,后端只是沒有反應。前端服務創建正確的 url,進行呼叫,沒有錯誤.. 后端什么也沒有收到。
我嘗試更改獲取請求,丟失路徑變數并使用 RequestBody,創建一個回傳字串的簡單測驗控制器,.. 似乎沒有任何作業了,除了已經是他們的東西。我究竟做錯了什么 ?為什么這個特定請求沒有到達我的后端?
角度服務:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable({
providedIn: 'root'
})
export class ProductService {
url = "http://localhost:8080/products/";
constructor(private http: HttpClient) { }
extendDateWithMonths(month : number, id:number | undefined): Observable<Response> {
console.log("service reached");
console.log("month: " month);
console.log("id: " id);
const specificUrl = this.url "extenddate/" `${month}` "/" `${id}`;
console.log("url: " specificUrl);
return this.http.post<any>(specificUrl, month, httpOptions);
}
}
控制臺輸出請求:
- 服務到達
- 月:3
- 編號:1
- 網址:http://localhost:8080/products/extenddate/3/1
在本地主機 8080 上運行的 java 后端控制器:
@RestController
@RequestMapping("/products")
@CrossOrigin(exposedHeaders = "http://localhost:4200")
public class ProductController {
@Autowired
ProductService productService;
@PostMapping("/extenddate/{month}/{id}")
public ResponseEntity<?> extenddate(@PathVariable int month, @PathVariable long id){
System.out.println("extenddate reached");
productService.extendProductsFromBon(month, id);
return ResponseEntity.ok(new MessageResponse("date extended successfully!"));
}
}
為什么這個特定請求沒有到達我的后端?為什么我沒有從控制臺收到錯誤或任何資訊?它要么可以到達 restapi,要么不能,但這很奇怪。
uj5u.com熱心網友回復:
您呼叫該方法,這就是您看到控制臺日志的原因。然而,回傳值是一個冷的可觀察值。為了實際將請求發送到后端,您需要訂閱可觀察物件。
我希望您只需在某處呼叫這樣的方法:
const response = this.productService.extendDateWithMonths(1, 2);
你需要做什么:
this.productService.extendDateWithMonths(1, 2).subscribe(
response => this.response = response;
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/534426.html
標籤:爪哇有角度的网址控制器
