Angular 打字稿连接数字而不是添加

Angular typescript concatenating numbers instead of adding

我有三个用户,当我点击下一步时,它必须为下一个用户加载路由,所以我将一个添加到 id 并传递给 routerLink,但不知何故而不是添加它连接数字,下面是代码

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute,Params } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit,OnDestroy {
  routeSubscription : Subscription;
  id : number;
  next :  number = 0;
  constructor(private route:ActivatedRoute) { 
  }

  ngOnInit() {
  this.routeSubscription =  this.route.params.subscribe((params :Params) =>{
    this.id = params['id'];
    this.next = this.id  + 1;
  });
  }
  ngOnDestroy(){
    this.routeSubscription.unsubscribe();
  }
}

Html 此模板

<p>
  user id : {{ id }}
</p>

<button class="btn btn-primary" [routerLink] = "['/Users', next ]">Next</button>

请告诉我为什么 next 与 id 连接

可能问题是this.id = params['id']设置一个字符串为this.id,然后'this.id + 1;'与“'1'”相同+ 1";

尝试将其解析为整数

this.id = parseInt(params['id'], 10); 

问题是 this.id = params['id']; 中的 params 对象返回的 id 值是一个字符串值。

以下应该可以解决您的问题

this.next = +this.id  + 1; // The id is cast to a number with the unary + operator

TypeScript 仅在编译时进行类型检查,这是失败的示例之一。问题是 Paramsdefined like this:

export type Params = {
  [key: string]: any
};

这意味着 params['id']any 类型,因此可分配给 number 类型的字段,即使它在运行时实际上是 string

因此,正如其他人已经指出的那样,您必须在分配之前解析该字段:

this.id = parseInt(params['id'])