我想在一个单独的卡组件中显示学生信息,但我无法将数据正确传递到此卡,我得到一个错误说:“加载资源失败:服务器以状态404()”响应。
student.component.html
<a [routerLink]="['/card', student.getId()]">
<button type="button" class="btn btn-info w-100" (click)="toggleCard(student)">Info</button>
</a>
student.component.ts
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.css'],
})
export class StudentComponent implements OnInit {
students: Student[] = [];
student: Student | undefined;
public showCard: boolean = false;
constructor(private studentService: StudentService, private route: ActivatedRoute) {}
ngOnInit(): void {
this.getAllStudents();
const id = this.route.snapshot.paramMap.get('id') || '';
this.studentService.getStudentById(id).subscribe(student => this.student = student);
}
public toggleCard(student: Student): void {
this.showCard = !this.showCard;
}
card.component.html
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card" style="width: 100%;">
<img src="{{ student?.getImageUrl() }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ student?.getFirstName() }}</h5>
<p class="card-text">{{ student?.getEmail() }}</p>
<a href="{{ student?.getCin() }}" class="btn btn-primary">View Profile</a>
</div>
</div>
</div>
</div>
</div>
card.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { Student } from 'src/app/models/Student';
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent implements OnInit {
@Input() student: Student | undefined;
constructor() { }
ngOnInit(): void {
}
}
应用路由
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StudentComponent } from './components/student/student.component';
import { CardComponent } from './components/card/card.component';
const routes: Routes = [
{ path: 'student', component: StudentComponent },
{ path: 'card', component: CardComponent },
{ path: 'card/:id', component: CardComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
1条答案
按热度按时间7fyelxc51#
我怀疑你的
studend-card
是在加载路由之前加载的,因为id
是null,在你的http调用中它被''
替换了。这就是为什么你有一个404。您可以尝试: