【发布时间】:2018-06-06 10:23:34
【问题描述】:
我正在尝试从 here 重新创建 spring-boot angularjs 示例应用程序。
当我使用 ./mnvw spring-boot:run 运行应用程序时,显示以下错误:
[ERROR] ERROR in src/app/app.component.html(6,18): : Property 'id' does not exist on type '{}'.
[ERROR] src/app/app.component.html(7,23): : Property 'content' does not exist on type '{}'.
我的源代码与上面提供的链接相同,但为清楚起见,打字稿文件:
import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Demo';
data = {};
constructor(private http: HttpClient) {
http.get('resource').subscribe(data => this.data = data);
}
}
html文件:
<div style="text-align:center"class="container">
<h1>
Welcome {{title}}!
</h1>
<div class="container">
<p>Id: <span>{{data.id}}</span></p>
<p>Message: <span>{{data.content}}</span></p>
</div>
</div>
还有 java 控制器:
@SpringBootApplication
@Controller
public class AngularApplication {
public static void main(String[] args) {
SpringApplication.run(AngularApplication.class, args);
}
@GetMapping("/resource")
@ResponseBody
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
}
app.module.ts 文件导入 HttpClientModule。当我将应用程序提供给 localhost:4200 时,站点会加载但没有数据。
这个想法是为 /resource 请求提供服务,并为客户端返回一个带有正确键的对象,但键不存在和/或客户端无法识别。
如何正确地将生成的 id 和 hello world 内容传递给数据对象?
【问题讨论】:
-
您应该为
data属性提供正确的类型(带有 id 和内容的对象),以使编译器警告消失。 -
提供的链接中的工作示例代码也没有定义数据对象及其类型,我试图使代码尽可能接近该示例。
-
好吧。您第一次发布的错误正在抱怨这一点。否则,我建议您查看 UI 尝试调用的 URL,并确保它与后端的 URL 匹配。首先检查丢失/或不同的端口号。 :)
-
感谢您的建议和快速响应,我会尝试一下:)
标签: java angular typescript spring-boot