![](/img/trans.png)
[英]How does Angular know which Spring Boot REST API to invoke?
[英]How to call and use the spring REST POST API in my angular app which is returning string without body?
我正在嘗試從我的 spring 應用程序訪問 POST API 到 angular 但有點困惑如何在我的 angular 應用程序中使用和訪問給定的 API。
Spring REST API
@RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
給定的 API 從我的 oracle 數據庫中獲取歡迎消息詳細信息並返回一個字符串值。 我正在嘗試通過服務在我的 angular 代碼中訪問給定的 REST API。 我定義了郵政服務如下
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
const headers = {'content-type':'application/text'}
return this.http.put("http://localhost:8080/API/getWelcomeMessage",null,
{'headers':headers});
}
}
由於 post 方法需要三個 arguments URL、Body 和 header。但在我的例子中,我的 spring REST API 不包含任何正文並返回字符串。 因此,我將正文定義為 null 並將 header 類型更改為文本,因為默認情況下它是 JASON。
最后,我試圖通過將它注入我的組件來訪問給定的服務方法,如下所示 -
export class LoginComponent implements OnInit {
message:string;
constructor(private loginService : LoginService) { }
ngOnInit(): void {
this.loginService.welcomeMessageService().subscribe(
response =>{
console.log(response);
this.message = response;
}
)
}
}
但是當我嘗試將響應分配給字符串時,我收到錯誤消息,即無法將字符串分配給 object。我有點困惑為什么會出現此錯誤,因為我在定義服務時也將 header 類型更改為字符串但仍然出現錯誤。
如果有人在這方面指導我,那將是一個很大的幫助,因為我是 angular 的新手,並且有點混淆 API 與 angular 的集成部分。
使用{ responseType: 'text' }
並發送一個空體而不是 null
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
return this.http.put("http://localhost:8080/API/getWelcomeMessage",{},
{ responseType: 'text' });
}
}
也許您將 function 復制錯了,但也請檢查此處
@RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
這是一個 Post 方法,而不是您要調用的 put
至於 cors 錯誤,無論你有什么,都將以下內容添加到@Controller
或@RestControler
上方的后端
@CrossOrigin(value = {"http://localhost:4200"}, methods = {GET,POST,PUT,DELETE})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.