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

问题描述 投票:0回答:3

我有三个用户,当我点击下一步它必须为下一个用户加载路由,所以我在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>

请让我知道为什么接下来会与id连接

angular typescript angular4-router
3个回答
5
投票

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

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

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

2
投票

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

尝试将其解析为整数

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

0
投票

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

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

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

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

this.id = parseInt(params['id'])
© www.soinside.com 2019 - 2024. All rights reserved.