单击迭代列表中的链接时,我正在使用带有激活路由的route参数重定向到另一个组件:
show-students.component.html
<table>
<tr *ngFor="let f of studentsfromapi | slice:0:10">
<td>{{f.userId}}</td>
<td><a [routerLink]="['/student-details', f.id]">{{f.id}}</a></td>
<td>{{f.title}}</td>
<td>{{f.completed}}</td>
</tr>
</table>
app.module.ts:
const appRoutes: Routes = [
{path: 'home', component: ShowStudentsComponent },
{path: 'student-details', component: studentDetailsComponent },
{path: 'student-details/:id', component: studentDetailsComponent },
{path: 'marks', component: MarksComponentComponent },
{path: '', redirectTo:'/home', pathMatch:'full' }
]
student-http-serv.service.ts:
getstudentDetailsHttpSrv(studentCode): Observable<IStudentHttp[]>{
return this._http.get('https://jsonplaceholder.typicode.com/todos' + studentCode)
.map((response:Response) => <IStudentHttp[]>response.json());
}
studentDetailscomponent.component.ts: 这是用于显示学生详细信息的服务被触发的文件
import { Component, OnInit } from '@angular/core';
import{ StudentHttpServService } from '../show-students/student-http-serv.service';
import {Router, ActivatedRoute} from '@angular/router';
import {Inject} from '@angular/core';
import {IStudentHttp} from '../show-students/servicehttp';
@Component({
selector: 'app-classes-component',
// templateUrl: './classes-component.component.html',
template: `
d<table>
<tr *ngFor="let studtls of studentsDetailsfromapi">
<td>{{studtls.id}}</td>
<td>{{studtls.title}}</td>
</tr>
</table>
`,
styleUrls: ['./classes-component.component.css']
})
export class studentDetailsComponent implements OnInit {
studentsDetailsfromapi:any;
constructor(@Inject(StudentHttpServService) private __astudentHttpServService: StudentHttpServService, @Inject(ActivatedRoute) private _activatedroute: ActivatedRoute, @Inject(Router) private _router:Router) {
}
ngOnInit() {
//this._StudentHttpServService.getstudentDetailsHttpSrv()
let studentCode = this._activatedroute.snapshot.params['id'];
/* this.__astudentHttpServService.getstudentDetailsHttpSrv(studentCode).subscribe(
(employeeData) =>{ this.studentsDetailsfromapi=employeeData; alert("this.studentsDetailsfromapi"+this.studentsDetailsfromapi)}
)*/
this.__astudentHttpServService.getstudentDetailsHttpSrv(studentCode).subscribe(
(employeeData) =>{alert("hi"); this.studentsDetailsfromapi=employeeData}
)
}
}
当我单击ID显示学生详细信息页面时,发生以下错误:
所以问题在于,由于以下功能而出现的网址:
let studentCode = this._activatedroute.snapshot.params['id'];
this.__astudentHttpServService.getstudentDetailsHttpSrv(studentCode).subscribe(
(employeeData) =>{alert("hi"); this.studentsDetailsfromapi=employeeData}
)
应为:https://jsonplaceholder.typicode.com/todos/3 and not
https://jsonplaceholder.typicode.com/todos3。因此问题在于'/'没有在id
之前附加(或者您可以说studentCode
)。
在 student-http-serv.service.ts 中,我尝试过:
return this._http.get('https://jsonplaceholder.typicode.com/todos' + '/' + studentCode)
但显示错误。
请帮助。谢谢。