首页 > 解决方案 > 从角度传递时,Spring Boot 无法识别路径变量数据

问题描述

我使用了 angualr 7 并将值从 angular 的服务类传递为:

executeHelloWorldBeanServiceWithPathVariable(name){
    console.log("name coming from here"+name);
    return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world/path-variable/${name}');
     console.log("hello world bean service executed");
   }

在我测试时,该名称正在控制台中打印:

console.log("name coming from here"+name);

它在控制台中打印,因为这里没有问题。

在此处输入图像描述

在我的春季靴子中,我声明为:

@GetMapping(path="/hello-world/path-variable/{name}")  
    public HelloWorldBean helloWorldBeanPathVariable(@PathVariable("name") String name) {
        System.out.print("name is"+name);
        return new HelloWorldBean(String.format("Hello world %s", name));
    }

当我尝试使用以下方法进行调试时,未打印我从 angular 传递的名称参数:

System.out.print("name is"+name);

但它显示在 el 表达式中

在此处输入图像描述

所以在我的用户界面中,我得到:

在此处输入图像描述

标签: javascriptjavaangularspringtypescript

解决方案


似乎您没有在方法中使用实际的模板文字语法executeHelloWorldBeanServiceWithPathVariable。我假设您因为${}表达式而尝试使用它。

这可能是请求未正确解析的原因。您应该使用反引号(`)而不是单引号或双引号。

executeHelloWorldBeanServiceWithPathVariable(name){
  return this.httpClient.get<HelloWorldBean>(`http://localhost:8080/hello-world/path-variable/${name}`);
}

此外,要从 API 请求中实际返回 observable,您必须在subscribe()需要它的组件上使用它。

例如,

constructor(
  private yourService: YourService,
) { }

ngOnInit() {
  this.yourService.executeHelloWorldBeanServiceWithPathVariable('someName').subscribe(res => {
    console.log(res);
    // do the rest here
  })
}

推荐阅读