【问题标题】:Angular typescript concatenating numbers instead of adding角度打字稿连接数字而不是添加
【发布时间】:2018-03-06 16:04:23
【问题描述】:

我有三个用户,当我点击下一个时,它必须为下一个用户加载路由,所以我将一个添加到 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.next = parseInt(this.id) + 1;
  • 我会在this.id = params['id']; 之后做console.log(typeof this.id) 来检查它是否仍然是数字
  • @RahulSharma 我已经将 id 声明为正确的号码
  • @YashwanthPotu URL 参数返回字符串,如果添加数字,它会更改为字符串。
  • 感谢@RahulSharma 了解使用 parseInt 或一元运算符,谢谢

标签: angular typescript angular4-router


【解决方案1】:

问题是this.id = params['id'];中的params对象返回的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); 

【讨论】:

  • 你为什么要在 parseInt 中加 10,我用了类似 this.id = parseInt(params['id']) 的东西,它起作用了
  • 你可以省略第二个参数,只要 10 是默认值。第二个参数是基数,换句话说,基数(二进制、十进制、十六进制等),正如这里所解释的 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 我习惯在我的角度应用程序中添加 10,因为默认的 lint 配置来自如果没有得到通知,angular-cli 会抛出错误。
【解决方案3】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2022-09-23
    • 2018-05-25
    • 2016-02-03
    • 1970-01-01
    相关资源
    最近更新 更多