我有一个JSON数据,当它在Parent组件中时会返回。您所需要做的就是在“父”组件上键入数字“ 12233”或“ 34567”,然后您可以在控制台上看到正在打印的数据。
就像孩子一样,我想通过使用来自父母的数据来打印 {{firstName}} 。
有没有一种方法可以使用stackblitz here
中的路由将数据属性传递给Child组件。父母: HTML:
<button class="btn-thumbnail">type the secret number to pass</button>
<!-- "number": 12233
or
"number": 34567 -->
TS:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import data from '../data.json';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor(private router: Router) {
document.addEventListener('keypress', this.secretNumber);
}
typed = '';
firstName : any = {};
secretNumber = event => {
this.typed += String.fromCharCode(event.keyCode);
let eraseData = [];
let matchedData = {};
if (this.typed.length == 5) {
Object.keys(data).length > 0 &&
data.items && data.items.userdata.map((item, i) => {
if(item.number == this.typed) {
matchedData = item;
console.log(item);
this.firstName = item.firstName;
console.log(this.firstName);
this.goToChild();
return matchedData;
}
if (item.number != this.typed) {
eraseData.push(item);
}
return eraseData;
});
if (Object.keys(matchedData).length == 0 && eraseData.length > 0 && this.typed.length == 5) {
this.typed = '';
}
}
};
ngOnDestroy() {
document.removeEventListener('keypress', this.secretNumber);
}
ngOnInit() {
}
goToChild() {
this.router.navigate(['/child'], { skipLocationChange: true });
}
}
Data.JSON:
{
"items": {
"userdata": [
{
"firstName": "john",
"lastName": "doe",
"number": 12233
},
{
"firstName": "mary",
"lastName": "jane",
"number": 34567
}
]
}
}
孩子: HTML:
<p>
child works! {{firstName}}
</p>
答案 0 :(得分:2)
当然,它的工作原理与您的示例相同。
将值作为queryParam
发送,如下所示:
goToChild(firstName) {
this.router.navigate(['/child'], { skipLocationChange: true, queryParams: {firstName} });
}
然后像这样在子路径上检索它:
public firstName?:string;
constructor(
private activatedRoute:ActivatedRoute
) { }
ngOnInit() {
this.activatedRoute.queryParamMap.subscribe(paramMap => this.firstName = paramMap.get('firstName'));
}
这是工作中的StackBlitz。
传递对象
如果要传递对象,最好的方法是将对象保留在服务中,并通过上述方法仅传递唯一的标识符。如果使用状态管理库,则应将对象而不是服务保存在此处。
我在您的示例中another StackBlitz对此进行了说明(我还整理了一些代码以使其更容易理解)。