I am new at learning Angular and Typescript, so I have a bit of trouble. I am working on an app that displays list of photos, allows us to create, edit and delete already existing photos. When I want to open the details page for a photo that doesn't exist, besides that I have a route activator that redirects to 404 not found page when the request is not valid, the page is still being loaded without any data. Here are the error messages I get "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 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
}
}
Here is my getPost function from the service:
getPost(id: number){
return this.http.get<Post>(this.apiUrl + "/" + id);
}
The code for the route:
{ path: 'posts/edit/:id', component: EditPostComponent, canDeactivate: ['canDeactivateCreateEvent'], canActivate: [PostRouteActivator] },
When I print the value of const postExists = !!this.postService.getPost(+route.params['id']);
in the console, besides the requested photo/post does not exist, the value I get is TRUE.
Can somebody please help me?