以下是代码:
在路由中选择匹配geting id,然后从URL
中获取此IDexport class MatchComponent implements OnInit {
_postArrayMatch: match[];
constructor(public router:Router, private matchService: MatchService,
private route: ActivatedRoute) {}
ngOnInit(){
this.getMatchId();
}
getMatchId() :void {
this.route.params.forEach((params: Params)=> {
let id = +params['id'];
this.matchService.getMatch(id).subscribe(
resultArray => this._postArrayMatch = resultArray,
error => console.log("Error ::" + error))
})
}
通过执行ngFor循环
进行基本插值 <div *ngFor="let post of _postArrayMatch">
<p>{{post.team1.name}}</p>
</div>
传递动态ID
getMatch(id:number): Observable<match[]>{
return this.http.get<match[]>(`http://localhost:3000/match/${id}`)
}
接口
export interface match{
team1:{
name:string,
id:number
}
team2:{
name:string,
id:number
}
}
答案 0 :(得分:0)
这似乎是我找到如何从对象获取数据的最简单方法。
objectKeys = Object.keys;
component.ts
$(".first-input").val()
答案 1 :(得分:0)
尝试在响应中创建对象的类似内容
<强> component.ts 强>
export class MatchComponent implements OnInit {
_postArrayMatch: match[];
newArr: Array<Object> = [];
constructor(public router:Router, private matchService: MatchService,
private route: ActivatedRoute) {}
ngOnInit(){
this.getMatchId();
}
getMatchId() :void {
this.route.params.forEach((params: Params)=> {
let id = +params['id'];
this.matchService.getMatch(id).subscribe(
resultArray => {
this._postArrayMatch = resultArray;
const keys = Object.keys(this._postArrayMatch) // new stuff starts here
for(let i = 0; i < keys.length; i++) {
newArr.push(this._postArrayMatch[keys[i]]);
newArr[i]['team'] = keys[i];
}
},
error => console.log("Error ::" + error))
})
}
然后您可以访问html中的所有子对象
<强> Component.html 强>
<div *ngFor="let post of newArr">
<p> {{post.team}}: {{post.name}}</p>
</div>
目前,您拥有的是第1组的强硬编码,如果您想这样做,那么您就不应该使用*ngFor