I'm trying to create an app in Angular but I get a "Type 'null' is not assignable to type 'number' error. The problem is that if I try to correct this error by using the "any" parameter in 'id', then the app does not show me the detail when I click on either panel on the front page.
The desired result would be that if I click on any panel:
The app should show me the detail:
This is my code:
service.ts:
import { Observable, of } from 'rxjs';
import { Ejercicio } from './ejercicio';
import { EJERCICIOS } from './collection-ejercicios';
@Injectable({
providedIn: 'root'
})
export class EjercicioService {
constructor() { }
getEjercicios():Observable<Ejercicio[]>{
return of(EJERCICIOS);
}
getEjercicio(id:number):Observable<Ejercicio>{
console.log("Id solicitado: "+id);
return of(EJERCICIOS.find(ejercicio=>ejercicio.id===id)!);
}
}
ejercicio.component.ts:
import { Ejercicio } from '../ejercicio';
import { EjercicioService } from '../ejercicio.service';
@Component({
selector: 'app-ejercicios',
templateUrl: './ejercicios.component.html',
styleUrls: ['./ejercicios.component.css']
})
export class EjerciciosComponent implements OnInit {
ejercicios!: Ejercicio[];
ejercicioSeleccionado:Ejercicio | undefined;
constructor(private ejercicioService: EjercicioService) {
console.log("---Componente Ejercicios CREADO ---");
}
getEjercicios():void {
this.ejercicioService.getEjercicios().subscribe(ejercicios=>this.ejercicios=ejercicios);
}
ngOnInit(): void {
console.log("---Componente Ejercicios[ngOnInit] ---");
this.getEjercicios();
}
onSelectEjercicio(ejercicio: Ejercicio): void {
console.log("Ejercicio seleccionado="+ejercicio.id);
this.ejercicioSeleccionado=ejercicio;
}
}
ejercicio-detalle.component.ts:
import { Component, Input, OnInit } from '@angular/core';
import { Ejercicio } from '../ejercicio';
import { ActivatedRoute } from '@angular/router';
import { EjercicioService } from '../ejercicio.service';
@Component({
selector: 'app-ejercicio-detalle',
templateUrl: './ejercicio-detalle.component.html',
styleUrls: ['./ejercicio-detalle.component.css']
})
export class EjercicioDetalleComponent implements OnInit {
ejercicio!: Ejercicio;
constructor(private route:ActivatedRoute, private ejercicioService: EjercicioService) { }
ngOnInit(): void {
this.getEjercicio();
}
getEjercicio():void{
const id=this.route.snapshot.paramMap.get('id');
this.ejercicioService.getEjercicio(id).subscribe(ejercicio=>this.ejercicio=ejercicio)
}
}
This is the line where I get the eror message:
I have managed to remove the error by adding id: any in the ejercicio.service.ts file, but in that case when I compile the application I don't get the desired result (the app does not show me the detail when I click on the front panels).
I would appreciate any help.
Thanks,