angular - 如何从另一个页面接收参数
问题描述
我正在做一个数字计算应用程序,我想将参数从一个页面传递到另一个页面,但我只得到第一个值。我该怎么做才能显示组件 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>
我希望输出作为我的应用程序中显示的所有值
解决方案
您将this.que.push({ firstNum, secondNum });
firstNum 和 secondNum 推入同一个数组对吗?
那么为什么不将整个数组发送到下一页,以便您可以按照您想要的方式访问它。
当需要时传递多个参数时,您当前所做的方式将会并且可能导致您在未来陷入代码混乱和可能的锁定。
所以,
this.router.navigate(['/operation', { que: this.que, answer: answer } ]);
这种方法将是有益的。
推荐阅读
- c# - 如何将对象从 aspx 代码后面传递到 Web 应用程序 angularjs 控制器?
- coq - WP 生成的 Coq 文件无法编译
- c# - 是否可以仅使用免费软件将文档转换为 PDF 或在 C# 中编辑 PDF?
- vba - 如果只能存在一个错误对象,那么声明 ErrObject 变量有什么用?
- nodes - Cytoscape 复合节点插入顺序
- image - 使用 CSS 缩小 SVG
- docker - 如何使用 docker-compose down 排除要删除的容器?
- go - 如何同时迭代 N 个文件以计算唯一单词的出现次数
- reactjs - VDOM 与虚拟 DOM 上的 React 性能时序
- d3.js - 使用不同颜色的 dc.js 显示原始(有条件的)刷过的未刷过的交叉过滤条