首先我想说我对 angular 和 typescript 都很陌生。
我用 angular 编写了一个程序,我使用路由在另一个页面上显示更多信息。
错误发生在 ngOnInit(){
出现第一个错误:this.blomId TS2322:输入“字符串” null '不可分配给类型'number'。类型 'null' 不能分配给类型 'number'。
第二个错误发生在:data[this.blomId] TS7053:元素隐式具有“any”类型,因为“number”类型的表达式不能用于索引“Object”类型。在“对象”类型上找不到带有“数字”类型参数的索引签名。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BlommorService } from '../blommor.service';
@Component({
selector: 'app-info',
templateUrl: './info.component.html',
styleUrls: ['./info.component.scss']
})
export class InfoComponent implements OnInit {
blomId: number;
valdblomma: any;
constructor(private activatedRoute: ActivatedRoute, private blomservice: BlommorService) {this.blomId = 0;}
ngOnInit() {
this.blomId =this.activatedRoute.snapshot.paramMap.get('id');
this.blomservice.getBlommor().subscribe((data) => {
this.valdblomma = data[this.blomId];
});
}
}
感谢您的帮助。
答案 0 :(得分:0)
this.blomId 根据声明应该是一个数字
blomId: number;
但是方法 this.activatedRoute.snapshot.paramMap.get() 返回一个字符串(如果找到匹配项)或 null(如果没有找到匹配项)。 因此,您将类型为 string 或 null 的值分配给类型为 number 的变量,因此 TS 会引发错误。
要修复它,您需要将 blomId 的类型更改为 string, 或使用 JS parseInt(string) 将字符串解析/转换为数字。
像这样:
this.blomId = parseInt(this.activatedRoute.snapshot.paramMap.get('id'));
但是请注意,如果函数没有找到匹配项,它将返回 null,如果您将 null 传递给 parseInt() 函数,则会得到 NaN。所以我们应该在解析之前添加一个检查以确保结果不是假的。
要修复您的两个错误:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BlommorService } from '../blommor.service';
@Component({
selector: 'app-info',
templateUrl: './info.component.html',
styleUrls: ['./info.component.scss']
})
export class InfoComponent implements OnInit {
blomId: string;
valdblomma: any;
constructor(private activatedRoute: ActivatedRoute, private blomservice: BlommorService) {this.blomId = "0";}
ngOnInit() {
this.blomId =this.activatedRoute.snapshot.paramMap.get('id');
this.blomservice.getBlommor().subscribe((data) => {
if (this.blomId) {
this.valdblomma = data[parseInt(this.blomId)];
} else {
// else logic goes here
}
});
}
}
如果仍然出现错误,请控制台记录订阅中的数据对象。
答案 1 :(得分:0)
打字稿中的错误对于指示预期内容非常可靠。它告诉您 Route params 始终是字符串或空值,因此如果您希望 number 作为 this.blomId 的类型,则需要强制转换为 number。显然在这种情况下,它将为空。
显然 getBlommer 服务期望数据为 Object 类型。这意味着数据必须与 JavaScript 中实际 Object 对象的“形状”相匹配。由于 this[whatever] 不会出现在本机对象上,因此会引发此错误。
可能想要为 getBlommer 作为“数据”返回的内容使用 any 或定义特定类型。