typescript 我想在Angular中将数据传递给卡组件,但我得到了这个404错误

eqoofvh9  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(116)

我想在一个单独的卡组件中显示学生信息,但我无法将数据正确传递到此卡,我得到一个错误说:“加载资源失败:服务器以状态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 {}

这是student组件的结果(它可以工作,但我得到了这个控制台错误):

卡片组件(/undefined)!

7fyelxc5

7fyelxc51#

我怀疑你的studend-card是在加载路由之前加载的,因为id是null,在你的http调用中它被''替换了。这就是为什么你有一个404。
您可以尝试:

this.route.paramMap.pipe(
filter(params=>params.id),
map(params=>params.id)
switchMap(id=> this.studentService.getStudentById(id)
).subscribe(student => this.student = student);

相关问题