首页 > 解决方案 > 如何从另一个页面接收参数

问题描述

我正在做一个数字计算应用程序,我想将参数从一个页面传递到另一个页面,但我只得到第一个值。我该怎么做才能显示组件 2 中的其余值?

我从 page2 中的数组中获取第一个值,但无法获取 console.log 中的其他值

组件1.ts:-

for (var i = 0; i < this.noQue; i++) { 
  var firstNum = Math.floor((Math.random() * divider));
  var secondNum = Math.floor((Math.random() * divider));

  if (this.operation == 1) {
    var answer = firstNum + secondNum;
  }
  else if (this.operation == 2) {
   var answer = firstNum - secondNum;
  }
  else if (this.operation == 3) {
    var answer = firstNum * secondNum;
  }

  this.answers.push(answer);
  this.answers1.push(answer);
  this.que.push({ firstNum, secondNum });
  this.ques.push({ firstNum, secondNum });
}

console.log('que---', this.que)
console.log('ans---', this.answers)

this.router.navigate(['/operation', { firstNum, secondNum, answer } ]);

Component2.ts:-

export class OperationComponent implements OnInit {
  f:[];
  fa:[]; 
  answer:[]; 
  que:[]
  constructor(private route: ActivatedRoute) { } 

  ngOnInit() {
    this.f = parseInt(this.route.snapshot.paramMap.get("firstNum"));
    this.fa = parseInt(this.route.snapshot.paramMap.get("secondNum")); 
    this.answer = parseInt(this.route.snapshot.paramMap.get("answer")); 
  }

component2.html:-

<div class="container"> 
  <h3 class="h2 text-center"> Grade </h3>
  <h3 class="h2 text-center"> Questions </h3> 
  <div class="card-block">
    <h4 class="card-title text-center"> {{f}} </h4> 
    <h4 class="card-title text-center"> +  {{fa}} </h4> 
    <p class="card-title h5 text-center"> _____</p> 
    <h4 class="card-title text-center"> {{answer}} </h4> 
    <button (click)="goBack()" [routerLink]="['']">go back</button>
  </div>
</div>

我希望输出作为我的应用程序中显示的所有值

标签: angular

解决方案


您将this.que.push({ firstNum, secondNum });firstNum 和 secondNum 推入同一个数组对吗?

那么为什么不将整个数组发送到下一页,以便您可以按照您想要的方式访问它。

当需要时传递多个参数时,您当前所做的方式将会并且可能导致您在未来陷入代码混乱和可能的锁定。

所以,

this.router.navigate(['/operation', { que: this.que, answer: answer } ]);

这种方法将是有益的。


推荐阅读