How is it possible to receive a TRUE value when the API returns an error message indicating that the requested photo does not exist?

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

const postExists = !!this.postService.getPost(+route.params['id']);
in the console is TRUE. Could someone please assist me? https://i.sstatic.net/oRJit.jpg

Answer №1

If the error is handled properly, solving this issue should be straightforward. In your PostRouteActivator,

Instead of simply

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

You could try the following:

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

});
    
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When Axios is disconnected, the sequence of events following a user's action is no longer dependent on when it is called after a button

I am working on a script that performs the following actions: Upon clicking a button, an encoded text is sent to an API for decoding. The decoded text is then used as a query for a Google search link that opens in a new tab. JAVASCRIPT // Summary: // ...

An issue has occurred: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent

I've been working on implementing Google Auth login with Firebase, but I keep encountering an issue when trying to load another component or page after logging in. I've spent the entire day trying to debug this problem and it's really frustr ...

Using a function to implement *ngFor results in generating a loop

When using *ngFor in Angular with a function that returns data, the function gets called multiple times and can sometimes result in a loop: app.component.ts export class AppComponent { getArray(): string[] { //I can track when this function is c ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

I am experiencing an issue where the button I place inside a material-ui table is unresponsive to clicks

Here is the structure of my table: <TableContainer component={Paper} style={{height: "40vh", width: "90vh"}}> <Table size="small" sx={{ minWidth: 200 }}> <TableHea ...

Navigating following a JQuery AJAX request in PHP

After clicking the login button, I utilize JQuery's POST method to retrieve data from login.php to check if the login was successful. If it fails (no user found), the appropriate message is displayed. However, when attempting to redirect a user (whic ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue: NestJS - Inject factory provider into another provider doesn't work I'm trying to set up an async provider that retrieves configurations from a remote repositor ...

Tips for transferring an excel file to a C# controller from Angular 4 within Visual Studio 2017

I'm working on a web application where I need to import an Excel file and send it to the server-side controller. On the server-side, I am utilizing EPPlus for this task. Can anyone provide guidance on how to accomplish this? I would greatly appreci ...

Searching for a specific element in jQuery by querying a string

I have a situation where an ajax request is made to send text using the POST method to another PHP page. This PHP page then converts the text into markdown format and sends it back. Here's an example of what it looks like: "<p>Meep, meep, <e ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Unable to access content using file_get_contents on php file

Query: $btc38="http://api.btc38.com/v1/depth.php?c=ltc&mk_type=btc"; $btc38_r=file_get_contents($btc38); $btc38_a=json_decode($btc38_r,true); I have successfully implemented APIs from other websites, but the one mentioned above is not functioning as ...

Is the array index a string or a number?

Why is it that when looping over the indexes of an array they appear as strings, even though using a string to index an array is not allowed? Isn't this inconsistency puzzling? for (const i in ["a", "b", "c"]) { console.log(typeof i + " " + i + " " ...

Scroll to make the div slide in from the bottom

I'm trying to achieve a similar effect like the one shown in this website (you need to scroll down a bit to see the divs sliding in). Although I'm not very proficient in JS, I was able to create a code that makes the divs fade in from 0 opacity ...

Differences between Strings and Constants in React While Using Redux for Action Types

In the Redux guide, it is suggested to define strings constants for Redux action types: const FOO = 'FOO'; const BAR = 'BAR'; dispatch({ type: FOO }); It's worth noting that most concerns raised are relevant to untyped JavaScrip ...

Querying a document by its Id using only JSON in MongoDB

I am trying to query a document in Mongodb (2.6.1) using pure JSON without using ObjectIds. According to the mongodb extended json documentation, I expected the code db.collection.findOne({"_id": {"$oid": "51b6eab8cd794eb62bb3e131"}}) to work but it is th ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...

Trigger a function when a button is clicked

This is an ongoing project that includes a calculator and other features. Right now, I am working on a functionality where when you input a number into the calculator results and press "+", it should trigger onClick to check if the input was an integer o ...

Is React dependent on the render process to update its state?

In my code, I am encountering an issue where the state of a key is not updating correctly even after performing operations on its value within a function. The scenario involves a function named clickMe, which is triggered by an onClick event for a button ...