ค้นหาเว็บไซต์

Angular typescript การต่อเลขแทนที่จะบวก


ฉันมีผู้ใช้สามคน เมื่อฉันคลิกต่อไป มันต้องโหลดเส้นทางสำหรับผู้ใช้คนต่อไป ดังนั้นฉันจึงเพิ่มหนึ่งใน 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

คำตอบ #1

ปัญหาคือค่าของ id ที่ถูกส่งกลับโดยวัตถุ params ใน this.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); 

บทความที่เกี่ยวข้อง