【问题标题】:Type 'string | null' is not assignable to type 'string | undefined'. Type 'null' is not assignable to type 'string | undefined'键入'字符串 | null' 不可分配给类型 'string |不明确的'。类型 'null' 不能分配给类型 'string |不明确的'
【发布时间】:2021-12-18 18:34:15
【问题描述】:

当我将属性设为 id!:string;或 id:string='';当我分配参数的值时,我得到一个错误

(属性)MoreParametersComponent.id:字符串 ts(2322)类型'字符串| null' 不可分配给类型 'string'。 类型 'null' 不能分配给类型 'string'。

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-more-parameters',
  templateUrl: './more-parameters.component.html',
  styleUrls: ['./more-parameters.component.css']
})
export class MoreParametersComponent implements OnInit {
  id!: string; // or id:string='';
  id2:number=0;
  constructor(private activatedRoute:ActivatedRoute) { }

  ngOnInit(): void {
    this.activatedRoute.paramMap.subscribe(params=>{
      this.id=params.get('id'); // gives the above error here
      this.id2=parseInt(params.get('id2'));//error
    });
  }

}

如何解决此错误?

我的其余代码:

app.component.html

<a routerLink=""> Home </a><br>
<a routerLink="one-parameter,'p01'"> One-Parameter </a><br>
<a routerLink="more-parameter,{id:'p02',id2:123}"> More-Parameter </a> 
<br><br>
<router-outlet></router-outlet>
<br><br>

Route.config.ts

import { Routes } from '@angular/router'
import { HomeComponent } from './home/home.component';
import { MoreParametersComponent } from './more-parameters/more-parameters.component';
import { OneParamterComponent } from './one-paramter/one-paramter.component';


export const mainroute:Routes=[
    {path:'',component:HomeComponent},
    {path:'one-parameter',component:OneParamterComponent},
    {path:'more-parameter',component:MoreParametersComponent}
];

【问题讨论】:

  • 到底是什么问题?看起来params.get 可能会返回null,而null 不能分配给this.id。你需要处理这种情况。
  • 现在我通过添加一些关于这个问题的必要代码来对我的代码进行一些更改。
  • 您可以随时使用this.id=params.get('id') || nullthis.id2=parseInt(params.get('id') || 0)
  • 只需将"strictPropertyInitialization": false 设置在tsconfig.jsoncompilerOptions 并赋值。我认为处理这个只是不必要的开销。
  • id: string | null;

标签: angular typescript


【解决方案1】:

ParamMap.get 的返回值是 string | null,它与您的 id 类型不匹配。

您可以将 ParamMap.get 的返回值转换为 params.get('id') as string 之类的字符串

或者您可以订阅params,而不是返回一个属性类型为any 的对象,并将id 参数作为对象键params.id 访问。见https://angular.io/api/router/Params

【讨论】:

  • 谢谢!! Mehyar 用于响应。
  • 通过as string“铸造”它只会告诉编译器将值视为字符串。事实上,它仍然很可能是一个null 值,并在此过程中导致错误。更好的解决方案是添加一个额外的检查值是否为空,并且仅在返回值是有效的可用值时才使用它。
  • 在此过程中会出现什么样的错误?当 null 作为参数传递时,这意味着问题发生在路由传递错误的 ID 参数值之前。在从参数接收 ID 值之前,应该防止这种情况发生。当然,在激活的 Route 中检查 ID 值也不错,但也不是绝对需要
猜你喜欢
  • 2021-06-12
  • 2018-04-05
  • 2021-07-14
  • 2021-04-10
  • 2021-09-06
  • 1970-01-01
  • 2021-09-30
  • 2022-01-27
  • 2022-01-17
相关资源
最近更新 更多