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

Spring Security与Angular官方教程Angular部分编译失败问题咨询

问题原因

这个问题不是教程核心逻辑过时,也不是你操作有错误,是新版本Angular默认开启的严格模板类型检查导致的报错:

  • 你代码中greeting的初始值是空对象{},TypeScript推导其类型为{},该类型上不存在id和content属性,因此Angular的模板类型检查会抛出变量未解析的提示。

修复方案

方案1(推荐,保留类型检查能力)

首先定义对应的数据类型,同时处理空值情况:

  1. 修改TS组件代码:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// 定义返回数据的类型接口
interface Greeting {
  id: number;
  content: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Demo';
  // 将greeting声明为可选的Greeting类型
  greeting?: Greeting;

  constructor(private http: HttpClient) {
    // 给get请求指定泛型类型
    http.get<Greeting>('resource').subscribe(data => this.greeting = data);
  }
}
  1. 修改HTML模板,使用可选链操作符处理空值:
<div style="text-align:center" class="container">
  <h1>
    Welcome {{title}}!
  </h1>
  <div class="container">
    <p>Id: <span>{{greeting?.id}}</span></p>
    <p>Message: <span>{{greeting?.content}}!</span></p>
  </div>
</div>

方案2(临时规避,不推荐)

如果不需要类型检查,可以直接将greeting声明为any类型,即可消除报错:

export class AppComponent {
  title = 'Demo';
  greeting: any = {};
  // 其余代码保持不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:18:03