Tips for updating a key value in a response using Angular HTTP

After receiving a JSON response, I found that the ImagePath URLs are redirecting to different locations when combined with the domain name.

[{
        "ImagePath": "/folder/images/products/1.jpg",
        "LanguageId": 2,
        "Id": 2,
    },
    {
        "ImagePath": "/folder/images/products/2.jpg",
        "LanguageId": 3,
        "Id": 3,
    }
]

The intended URL structure was www.getimage.com + imagepath, but after hitting the URLs, they were redirected elsewhere.

e.g. www.getimage.com/folder/images/products/2.jpg

This redirection issue is causing problems. How can this be resolved?

Answer №1

To improve your code, you may need to provide more information on how you invoke the get method. However, based on my understanding, if you always receive an array of a certain kind, you can potentially solve it using a pipe and ImagePath mapping transformation. Here is an example:

import { map } from 'rxjs/operators';


return this.http
.get<SearchImageResponse[]>(this.url, { params})
.pipe<SearchImageResponse[]>( 
    map ( (_responseArray: SearchImageResponse[]) => (_responseArray.map( image =>  image.ImagePath = 'www.getimage.com' + image.ImagePath ) ) )
);

Make sure to adjust the code with your specific URL, params, and data type.

If you prefer working within a subscribe block:

this.http
.get<SearchImageResponse[]>(this.url, { params})
.pipe<SearchGifResponse[]>( 
    map ( (_responseArray: SearchImageResponse[]) => (_responseArray.map( image =>  image.ImagePath = 'www.getimage.com' + image.ImagePath ) ) )
)
.subscribe((response) => {
    // Ensure response remains a SearchImageResponse[]
    response = response.map( (_responseArray: SearchImageResponse[]) => (_responseArray.map( image =>   image.ImagePath = 'www.getimage.com' + image.ImagePath ) ) );

}

Another alternative approach:

let transformedArray:SearchImageResponse[] = [];

this.http
.get<SearchImageResponse[]>(this.url, { params})
.pipe<SearchGifResponse[]>( 
    map ( (_responseArray: SearchImageResponse[]) => (_responseArray.map( image =>  image.ImagePath = 'www.getimage.com' + image.ImagePath ) ) )
)
.subscribe((response) => {
    // Ensure response remains a SearchImageResponse[]
        this._historialBusqueda.forEach( _img => {

      _img.ImagePath = 'www.getimage.com' + _img.ImagePath;

       transformedArray.push(_img);


    });
}

Please note that I cannot test this at the moment, so I'm not certain if it will work. Nevertheless, I hope this guidance proves helpful.

Answer №2

Based on your title, it appears you are looking to translate the key values in your response to new values?

res.map( elem => {
    elem.ImagePath = elem.ImagePath.replace('/folder/images/','/protected/cart/img/');
})

However, the remainder of your message indicates that you may be experiencing an issue with a redirect, which seems unrelated to your initial query.

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

Trouble with Angular not redirecting to external URLs using anchor tags

I'm having difficulty getting a basic link to function in Angular. When I place it in the app component without any other components, it works fine. However, when I move it inside a child component, it stops working. Clicking on the link does nothing ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...

How can I stop the page title from automatically updating in Joomla 1.5?

Currently, I am dealing with a chaotic Joomla project where much of the functionality is hardcoded in the core. For example, passing option=com_admn&view=displayUsers. One particular issue we are facing involves our blog page, where all blogs are dis ...

remove function erases all the data in Vue

My goal is to delete only the item that has been clicked on. todoList Component: template : <ul class="list-group"> <todo v-for="(todo,i) in todo" :key="i" :todoString="todo.todoString" : ...

Submitting the object in the correct format for the Firebase database

My goal is to structure the Firebase database in the following way: "thumbnails": { "72": "http://url.to.72px.thumbnail", "144": "http://url.to.144px.thumbnail" } However, I am struggling to correctly set the keys '72' and '144&apos ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

Remove a textbox dynamically in jQuery using solely jQuery without the use of traditional JavaScript code

My code is aimed at creating a dynamic way to add and remove textboxes. However, I am encountering a problem where clicking the delete button removes everything instead of just one textbox. Can anyone spot the error in my code or offer a solution to remo ...

Search two arrays in a loop and identify variations with a unique approach

Currently, I am facing a challenge that I need assistance with. I am working on an updater that retrieves an XML list of files from a CDN and compares it with an older list to identify any file differences. The objective is to determine which files are out ...

Initiating a post request that triggers every if/else statement and redirects accordingly

For my initial express project, I am working on a login page. Unfortunately, when I send a post request with an if/else statement to redirect users based on their input, all the if else statements are executing and triggering an error message that states ...

How did I end up facing two distinct decimal separators side by side like this?

As I find myself in France where the decimal separator is a comma, I have created this component that showcases a discrepancy in displaying numbers: Both commune.population and commune.surface are decimal numbers (with the type number) However, they unexp ...

Angular logs the HTTP error before it is processed

When a user clicks on a button on a simple login form, a mechanism is triggered. This mechanism involves sending a POST request to a REST service with the user's provided credentials. If the credentials are correct, the success function is executed, o ...

Creating a recursive function using NodeJS

This particular challenge I am tackling is quite intricate. My objective is to develop a recursive function in NodeJS that can interact with the database to retrieve results. Based on the retrieved data, the function should then recursively call itself. F ...

Creating interactive and adaptable maps

Currently, I am working on making a Joomla website responsive. However, I have encountered an issue with the SobiPro Map. The problem arises when displaying a map (background img) and points (a link + img) over it with an absolute position. As a result, wh ...

Using jQuery to check if a value exists in a PHP array

I am encountering an issue with handling an array in PHP and using it in my jQuery code. Previously, I was able to successfully work with the array when it was a string, but now that it is more complex, the comparison of elements is not functioning properl ...

Instantly see changes without having to manually refresh the screen

I need help figuring out how to update my PHP webpage or table automatically in real-time without requiring a manual refresh. The current functionality of the page is working perfectly fine. Specifically, I want the page to instantly display any new user ...

Struggling to grasp the importance of ensuring the security of axios requests

I am struggling to grasp the security implications of using Axios requests. Situation I have a basic button that allows users to register with a random string through a post request. This post request is then processed by my express server, which ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

I'm attempting to install React, but I keep encountering the error mentioned below. What steps can I take to resolve this issue?

Having trouble installing using the command: view image description here PS D:\Programming\Js\React> npx create-react-app my-app npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\Users\NGUYEN THI PHUC&bsol ...

How can I reorganize an object array into key value pairs using Javascript and then save it to mongoose and MongoDB for storage or outputting purposes?

Having just started with JS and utilizing node.js, express, and mongoose, I find myself working with an incoming array containing random key-value pairs that are unpredictable. // For example const simpleArray = { d: "h", e: "i", f: "j" ...

Ways to resubmit a HTML form

UPDATE: I made a silly error. Accidentally used some outdated code where the 'start' function became inactive after being clicked. It's all sorted out now. Lesson learned: meticulously review your code line by line, especially if it's a ...