I am currently in the process of learning Angular and Typescript, but I am facing some challenges. I am working on an application that involves displaying a list of photos, as well as allowing users to create, edit, and delete existing photos. However, when attempting to open the details page for a photo that does not actually exist, despite having a route activator set to redirect to a 404 not found page for invalid requests, the page still loads without any data. I am encountering the following error messages: "Failed to load resource: the server responded with a status of 404 ()" and "core.js:4197 ERROR HttpErrorResponseerror: {}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}message: "Http failure response for https://jsonplaceholder.typicode.com/photos/5453453: 404 OK"name: "HttpErrorResponse"ok: falsestatus: 404statusText: "OK"url: "https://jsonplaceholder.typicode.com/photos/5453453"proto: HttpResponseBase defaultErrorLogger @ core.js:4197 ".
Here is the code for my route-activator :
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router'
import { Injectable } from '@angular/core'
import { PostsService } from './posts.service'
@Injectable()
export class PostRouteActivator implements CanActivate{
constructor(private postService: PostsService, private router: Router ){
}
canActivate(route:ActivatedRouteSnapshot){
const postExists = !!this.postService.getPost(+route.params['id']);
console.log(postExists)
if (!postExists){
this.router.navigate(['/404']);
}
return postExists
}
}
This is my getPost function from the service:
getPost(id: number){
return this.http.get<Post>(this.apiUrl + "/" + id);
}
The code snippet for the route configuration:
{ path: 'posts/edit/:id', component: EditPostComponent, canDeactivate: ['canDeactivateCreateEvent'], canActivate: [PostRouteActivator] },
Despite the requested photo/post not actually existing, the value I receive when echoing
in the console is TRUE.
Could someone please assist me?
https://i.sstatic.net/oRJit.jpgconst postExists = !!this.postService.getPost(+route.params['id']);