0

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? enter image description here

cipherxxx
  • 15
  • 4

1 Answers1

0

I feel if you handle the error properly then this problem will get easily. So in your PostRoutActivator

Instead of just

@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
  }
}

If you can

 @Injectable()
    export class PostRouteActivator implements CanActivate{
      constructor(private postService: PostsService, private router: Router ){
    
      }
    
      canActivate(route:ActivatedRouteSnapshot){
        const postExists = this.postService.getPost(+route.params['id'])
           .pipe(
               catchError((err)=>{ // make sure you import this operator
                if(err.statusCode == 404) // not sure which property would be just console.log the err and you will know.
                {
                   return false;
                } else {
                   throw err;
               }
             })
           ).subscribe((postExists) => {
               console.log(postExists)
                if (!postExists){
                 this.router.navigate(['/404']);
                }
                return postExists
           }

});
    
}