2

我想首先说我对 angular 和 typescript 都很陌生。

我用 Angular 编写了一个程序,我使用路由在另一个页面上显示更多信息。

错误发生在 ngOnInit(){

第一个错误发生在:this.blomId TS2322: Type 'string | null '不可分配给类型'数字'。“null”类型不能分配给“number”类型。

第二个错误发生在:data[this.blomId] TS7053:元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引“对象”类型。在“对象”类型上找不到具有“数字”类型参数的索引签名。

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];
    });
  }
}

感谢帮助。

4

2 回答 2

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
      }
    });
  }
}

如果您仍然收到错误,请控制台记录订阅中的数据对象。

于 2021-01-10T22:08:52.040 回答
0

打字稿中的错误对于指示预期内容非常可靠。它告诉您 Route 参数始终为字符串或 null,因此如果您希望 number 成为 this.blomId 的类型,则需要转换为 number。显然在这种情况下,它将为空。

显然 getBlommer 服务期望数据是对象类型。这意味着数据必须与 JavaScript 中实际 Object 对象的“形状”相匹配。由于 this[whatever] 不会出现在本机 Object 上,因此会引发此错误。

可能想要为 getBlommer 作为“数据”返回的内容使用任何类型或定义特定类型。

于 2021-01-10T22:18:20.013 回答