问题
I have a json response like this.
{
"response": {
"data": {
"students": [{
"studentsNumber": "123",
"studentsName": "ABC"
}, {
"studentsNumber": "345",
"studentsName": "CDS"
}]
}
}
}
I am doing a request to get the response data. I have a html where i am displaying list with the response data. My requirment is on click of each list item it should redirect to next html page.For that in the routerLink i am passing studentsNumber like this students.component.html
<div *ngFor="let student of studentsData" routerLink="/studentdetails/:{{student.studentsNumber}}" routerLinkActive="active">
<div>{{student.studentsNumber}}</div>
<div>{{student.studentsName}}</div>
</div>
And in the studentdetails.component.ts
constructor(route:ActivatedRoute) {
this.stuID = route.snapshot.params['studentsNumber'];
}
ngOnInit(){
this.studentdetailsData = this.studentdetailsService.loadStudentsDetails(this.stuID);
}
And in studentdetails.service.ts
loadStudentsDetails(studentNumber:number){
this.studentDetailsData= this.studentsData.filter(ob => ob.id===Number);
return this.studentDetailsData;
}
In loadStudentsDetails how can I get details of the perticular student by using the studentsNumber. I am trying like this but In the next screen i am getting all the studentdetails not one perticular student details Can anyone please help me how to do this.
回答1:
You've done a few things wrong, firstly inside your HTML where you're looping, you need to define the routerLink
as follows:
HTML
<div *ngFor="let student of studentsData" routerLink="['/studentdetails/', student.studentsNumber]" routerLinkActive="active">
<div>{{student.studentsNumber}}</div>
<div>{{student.studentsName}}</div>
</div>
Inside the studentdetails component, you need to get the number through the ActivatedRoute
module, wait for the subscribe action and then only call the get details, please see below:
studentdetails.component.ts
ngOnInit(): void {
this.route.params
.subscribe((params: any) => {
this.stuID = params['id'] //not sure what your id is called here, it's defined in your route
this.studentdetailsData = this.studentdetailsService.loadStudentsDetails(this.stuID);
});
}
Your service, you need to select the first item by adding [0]
, it should look as follows:
loadStudentsDetails(studentNumber:number){
return this.studentsData.filter(ob => ob.id === Number)[0];
}
来源:https://stackoverflow.com/questions/46048438/how-to-redirect-to-next-page-by-passing-id-and-show-details-in-angular2