When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected.

const urlParams = { email: this.email };
this.voicesProfileObservable$ = this.service.request<any>(
  AVAILABLE_SERVICES.GET_USER_PROFILE_VOICES.ID,
  {},
  { urlParams }
).pipe(
  catchError((error) => {
    this.voicesProfileObservable$ = Observable.of({
      aboutSectionType: '',
      aboutCustomizedDescription: '',
      showSpacesFollowed: true,
      showBadgesEarned: true,
      showMobileNumber: true,
      showOfficeNumber: false,
      showEmail: true,
      showSlackHandle: false,
      video: {},
      socialLinks: [],
      personalLinks: [],
    });
    return throwError(error);
}))

Answer №1

The reason for the issue is that you are setting this.voicesProfileObservable$ multiple times. First, when you define and declare it as an observable, and then again in the catchError() block.

To resolve this, handle the error by catching it and returning with of(...data) instead of throwing the error.

          catchError(_ => of({
            aboutSectionType: '',
            aboutCustomizedDescription: '',
            showSpacesFollowed: true,
            showBadgesEarned: true,
            showMobileNumber: true,
            showOfficeNumber: false,
            showEmail: true,
            showSlackHandle: false,
            video: {},
            socialLinks: [],
            personalLinks: [],
          })

     

Answer №2

Here is a suggested way to approach it:

this.voicesProfileObservable$ = this.service.request<any>(
  AVAILABLE_SERVICES.GET_USER_PROFILE_VOICES.ID,
  {},
  { urlParams }
).pipe(
  catchError((error) => {
    return of({
      aboutSectionType: '',
      aboutCustomizedDescription: '',
      showSpacesFollowed: true,
      showBadgesEarned: true,
      showMobileNumber: true,
      showOfficeNumber: false,
      showEmail: true,
      showSlackHandle: false,
      video: {},
      socialLinks: [],
      personalLinks: [],
    });
  })
)

In order to pass the default response down to subscribers, it's recommended to directly return it within the catchError callback.

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

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

In Chrome, it seems like every alternate ajax request is dragging on for ten times longer than usual

I've been running into an issue with sending multiple http requests using JavaScript. In Chrome, the first request consistently takes around 30ms while the second request jumps up to 300ms. From then on, subsequent requests alternate between these two ...

Set up ExpressJS to utilize port 3000 for the server

I am working on an app where the backend is currently running on localhost:8000, but I need it to run on port 3000. Specifically, I am using an express server for this example. How can I configure it to run on the desired port? Below is my current server. ...

Discovering the generic parameter types with union in TypescriptUncover the

I've been struggling with the code snippets below for a while. Can someone explain why e4 is defined as string and not String? type PropConstructor4<T = any> = { new(...args: any[]): (T & object) } | { (): T } type e4 = StringConstructor ext ...

Guide on displaying JSON data from a server on a webpage using Google Charts in real-time

Although I am not a JavaScript developer or an expert in AJAX, I consider myself a novice desktop developer. I would greatly appreciate it if you could guide me on how to connect an MCU that returns JSON data to a web page using Google gauge, running on th ...

Issue - Unrecognized listen EADDRINUSE :::5432 detected in Windows Command Prompt

I encountered an issue when I tried running gulp serve --nobrowser, resulting in the following error: { Error: listen EADDRINUSE :::5432 at Object._errnoException (util.js:992:11) at _exceptionWithHostPort (util.js:1014:20) at Server.setupListenHandle [as ...

What is the best way to create a sticky div that reacts to a floating (position: fixed) div?

I have been utilizing Material UI's <Appbar /> component, which is rendered as a div with position: fixed;. The effect of the bar hiding on scroll employs visibility: hidden; and transform: translateY(-59px);. Now, my goal is to include a stick ...

Having trouble getting the `transformItems` feature in React InstantSearch RefinementList to

I recently integrated the React InstantSearch library into my app and I'm working on customizing the refinement list to display only relevant filters for the active user. I attempted the following code: <RefinementList attributeName="organization" ...

Guide for installing the uncompressed version of Angular2 with NPM

Is there a way to install the uncompressed version of Angular2 using NPM? This is how I usually do it: npm install angular2 ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

Implementing a click function that toggles between adding and removing a class, keeping track of the number of clicks, and utilizing localStorage to prevent repeated clicking in the

Hi there! I'm currently working on a simple widget that features a clickable icon and a counter next to it. When the icon is clicked, it should toggle between an empty heart and a filled heart using addClass/removeClass. Additionally, each click incr ...

How can I fill the data array of arrays using an Angular Table component?

I am struggling to populate an Angular Table with data in the array of arrays format. Despite my efforts, the code I have written does not seem to work. Any suggestions for a solution would be greatly appreciated. Here is the data that I am trying to popu ...

Leverage Reveal.js within Next.js by installing it as an npm package

I am currently working on a project that requires integrating Reveal.js with Next.js. However, I am having trouble displaying the slides properly. Every time I try to display them, nothing shows up. Even after attempting to display some slides, I still en ...

Shuffling arrays with JavaScript and jQuery for a touch of randomness

Looking to add some variability to your font choices? I've got an idea for you! How about randomizing three arrays for fonts, font size, and font weight? Then, we can display the results of these arrays in a div with the class name "randomFont." Each ...

Which is better: Angular 2 dedicated cache service or embedded cache management?

Our current project involves implementing complex cache management logic within various http services such as EmployeeService and DepartmentService. What would be the most optimal choice? Integrating cache logic directly into the model service classes ...

Iterating through an array with a .forEach loop and referencing the variable name

Currently, I am working on a project using JS/React and dealing with nested arrays in an array. The structure of my data looks like this: const ezra = ["Patriots", "Bears", "Vikings", "Titans", "Jets", "Bengals"] const adam = ["Chiefs", "Cowboys", "Packer ...

The error encountered is: `Exception: startDate.getTime is not a valid function

const [currentDate, setCurrentDate] = useState(new Date()); const fetchDataFromAPI = () => { let timeStamp = Number(currentDate.getTime()); axios.get( `https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD,EUR& ...

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Angular Ionic: Unable to compare 'value'. Only arrays and iterable objects are permitted for differentiation

I attempted to display a list value and when I logged the value of the list, it appeared exactly how I wanted: unit value {id: 81, name: "3 BR Suite"} unit value {id: 82, name: "3 BR Grande"} unit value {id: 83, name: "Pool Villa&q ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: https://i.sstat ...