Typescript: Add a new variable preceding a specified string

fetchArticle(articleId: string): Observable<any> {
    return this._http.get(`${this._url}/${articleId}`)
      .map((response: Response) => response.json())
      .do(value => console.log(value))
      .catch((error) => Observable.throw(error));
  }

Within the code snippet above, the http.get is making a request to a specific URL:

http://website.com/.json/5

If we want the {articleId} (which in this case is 5) to be placed before the .json extension, the URL should be structured like this:

http://website.com/5.json

Answer №1

It appears that the variable this._url is currently experiencing some issues. To resolve this, it is recommended to make necessary adjustments to the variable in order to facilitate easier manipulation. If modifying how the variable is calculated is not possible, your best option would be to replace the existing value with the following:

return this._http.get(this._url.replace(".json", articleId + ".json"))

Answer №2

Here is a solution for your issue (assuming that your URL already ends with the .json)

var url = 'www.example.com/.json'
var articleId = 2;
var newUrl = `${url.split('/.json')[0]}/${articleId}.json`
console.log(newUrl)

For your specific scenario:

retrieveArticle(articleId: string): Observable<any> {
    return this._http.get(`${this._url.split('/.json')[0]}/${articleId}.json`)
      .map((response: Response) => response.json())
      .do(data => console.log(data))
      .catch((error) => Observable.throw(error));
  }

Answer №3

When you are in charge of manipulating this.url, you can set it up with a placeholder for the id like so:

this._url = 'http://website.com/{articleId}.json';
...
return this._http.get('${this._url.replace('{id}', articleId))

This approach helps keep your code independent of the specific url structure.

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

Repeating every other item in a list using ng-repeat in AngularJS

Using AngularJS version 1.5.3 In my view, I have a list of items that I want to display. After every two items, I would like to show a new div below the first one. <div class="col text-center" ng-repeat="event in weekDay.events"> &nbsp;& ...

Managing the outcome of numerous asynchronous calls before accessing the database post-result collection

Hey everyone, I'm just getting started with node.js and I'm working on the following tasks: Calling the AWS API to create Cognito users by passing data. After all requests are completed, inserting all the records into the database. In my code, ...

Guide on exporting values from a Promise within an imported module

Recently, I encountered a challenge where I needed to integrate a pure ESM package into a non-module. Unfortunately, modifying the script to accommodate this requirement was not an option. To tackle this issue, I turned to using the import() function (als ...

Executing Ajax requests to interact with a RESTful API

After developing a back end REST API using Slim Framework and closely following the REST format, I ran into an issue when working on the Front End. It seems that AJAX functions well with parameters but not paths. I am considering outsourcing or creating a ...

Tips for showing or hiding the router-link button in a particular Vue.js component

Currently, I have implemented router-link as a button to switch between various components. However, I am interested in exploring ways to hide a specific component. <router-link :to="{path: prevPage }" tag="button" class="btn btn-primary"> ...

Utilizing the import feature for structuring the routes folder in Express with Node.js

Recently, I made the switch to using ECMAScript (ES6) for my NodeJS Rest API with Express, and I've encountered a few challenges when working with the new keyword import In the past, I would organize my routes folder like this: Let's imagine th ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...

Angular 6 - Outdated Functions

I'm having trouble updating the request options as they are now deprecated. I can't seem to locate the alternative option for this. Can anyone offer some assistance? import { Injectable } from '@angular/core'; import { HttpClient } fr ...

Accessing values using keys with special characters in Json can be done with the json-simple library

When working with a JSON object, I encountered an issue where I couldn't retrieve a value from a key because the key contained a special character $. Here is the JSON object in question: JSONParser parser = new JSONParser(); String str = "{\"$oi ...

Updating the dependencies in package.json is not reflecting the changes

Attempting to run my friend's project on my machine with the angular-cli led me to discover that the dependencies in the package.json were outdated. In an effort to update them, I used the following commands: npm i -g npm-check-updates npm-check-upda ...

Remove all input fields within an HTML file using a TypeScript method implemented in an Angular 2 component

Within my Angular project, there are several input elements in the HTML file that are not enclosed within a form tag. I am looking to create a function in the TypeScript file that will clear all of these inputs. I attempted to utilize ViewChild, but it a ...

A guide to automatically playing audio on a webpage using HTML and JavaScript

I'm currently in the process of developing a quiz application, and my goal is to have a sound play when a user enters the webpage to initiate the quiz. Initially, I attempted to use JavaScript to trigger the sound on page load, but unfortunately, the ...

Observables in Knockout.js vanish after being bound

I'm encountering a peculiar issue with my Knockout script. Here is the viewModel: viewModel = { viewShown: function () { if (params.id !== undefined) timer = setInterval(loadVorgangsdetails, 100); else { $( ...

Tips on how to save information from a command and retrieve it in discord.py

Currently, I am developing a Discord bot with a command called "addtoken" which prompts for a name and a contract. This command then adds the token to a dictionary. However, I am looking to persist these added tokens so that they are still available when t ...

React.js and Visual Studio Code have recently been causing unexpected and massive "Module not found" errors

Everything was going smoothly with my project until I uploaded it to Github and then cloned it. Suddenly, I started encountering various "Module not found: Can't resolve..." import errors. For example: Module not found: Can't resolve './co ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

Whenever I try to execute 'docker build --no-cache -t chat-server .', I always encounter type errors

Below is the Dockerfile located in the root directory of my express server: FROM node:18 WORKDIR /usr/src/server COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 RUN npm run build CMD ["npm", "start"] Here is the contents of my .dockerign ...

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

Best practices for using useEffect to fetch data from an API_FETCH in a certain condition

When retrieving state from an API using Zustand within a useEffect function, what is the recommended approach to do so? Currently, my implementation is quite straightforward: export interface ModeState{ modes: Mode[]; fetchModes: () => void; } expo ...