【发布时间】:2021-05-13 06:56:35
【问题描述】:
如何对返回的响应进行严格的角度类型检查。
1.data.json 文件用于临时 api 目的
[
{
"name": "Someone 1",
"comment": "comment 1",
"line": "line 1"
},
{
"name": "Someone 2",
"comment": "comment 2",
"line": "line 2"
},
{
"name": 3,
"comment": "comment 3",
"line": "line 3"
}
]
- 模型界面
export interface Model {
name: number;
comment: string;
line: string;
}
3.服务类app.service.ts
export class AppService {
constructor(private _http: HttpClient) {}
private api = "../api/data.json";
loadData(): Observable<Model[]> {
return this._http.get<Model[]>(this.api);
//.pipe(tap((data) => console.log("All:" + JSON.stringify(data))));
}
loadSingle(): Observable<Model> {
return this.loadData().pipe(map((data: Model[]) => data[2]));
}
}
4.component类app.component.ts
export class AppComponent implements OnInit {
myvarArray: Model[];
myvarSingleton: Model;
constructor(private _appService: AppService) {}
ngOnInit() {
this._appService.loadData().subscribe((data) => {
this.myvarArray = data;
});
this._appService.loadSingle().subscribe((data) => {
this.myvarSingleton = data;
console.log(data.name + ":" + data.comment);
});
}
}
5.app.component.html
<h1>Printing obj data</h1>
<ul *ngFor="let data of myvarArray">
<li>{{ data.name }} -- {{ data.line }}</li>
</ul>
<h1>Printing Single data</h1>
<span>{{ myvarSingleton.name }}</span>
什么是实现严格类型检查的方法,以便 data.json 中的值符合接口中声明的类型? 我的观点是,虽然当数据返回到 app.component 时,名称是以数字形式给出的,但它在编译时仍然不会显示任何错误,如果有某种方法可以隐式地检查这个而不是显式的验证函数?
[编辑] 另外,当在界面中明确定义了属性(但数据在页面上正确显示)时,为什么我会收到 myvarSingleton.name 上的未定义属性错误?为什么要调用 3 次?
【问题讨论】:
-
Typescript 是一种静态类型检查功能。在运行时 JavaScript 没有“严格”的类型检查。您需要编写代码以满足您的要求。
-
您好!为了将来参考,当您跳过问题本身的代码而不是屏幕截图时,我们可以更轻松地提供帮助。
-
能否请您添加源代码而不是图像?这将是一个伟大的!
-
格式化代码
标签: javascript angular typescript web frontend