Is it possible for me to add a string to a URL as long as the string is not null?

When retrieving data from a database, I have the option to include specific parts for a more targeted search.

Let's say I have an object structured like this:

{
  title: "wonderland",
  aliases: "",
  ...
}

My goal now is to generate a URL for the GET request.

getResults(obj){
    return this.http.get(`${this.url}/title=${obj.title}&aliases=${obj.aliases}`)
}

In this scenario where the property 'aliases' is empty as shown above, I want to exclude the part &aliases=${obj.aliases}. Similarly, if the 'title' property were empty, I'd want to eliminate title=${obj.title}.

How would you go about achieving this?

Answer №1

Give this a shot - it's a better alternative to what you're attempting

let data = {
  title: "enchanted",
  tags: ""
}

function addOptionalData(endpoint) {
  let count = 0;

  for(let param in data){
    if (data[param]) {
      if (count === 0 ) {
        endpoint = `${endpoint}/${param}=${data[param]}`
      } else {
        endpoint = `${endpoint}&${param}=${data[param]}`
      }
      count ++;
    }
  }

  return endpoint;
}

function retrieveData(obj) {
  let endpoint = `${this.url}`
  endpoint = addOptionalData(endpoint)

  return this.http.get(`${endpoint}`)
}

Answer №2

Here is a suggestion on how you can achieve this:


createAliasQuery(aliasList) {
    if (aliasList) return '&aliases=${aliasList}';
    return '';
}

fetchResults(data){
    return this.http.get(`${this.url}/title=${data.title}${createAliasQuery(data.aliases)}`)
}

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 using Sequelize, you may notice that extra spaces are automatically added at the end of the DataTypes.CHAR data type

Here is an example of how I structure my Store.ts file: import {DataTypes, Model, ModelAttributes} from "sequelize"; export default class Store extends Model { declare id: number declare name: string declare phone: string } export const S ...

Creating a connection object for MySql2 in TypeScript within a class

I'm still a beginner when it comes to TypeScript, so I often stumble over simple things. Initially, I had no issues creating a database connection using the code snippet below that was not placed inside a class: const mysql = require('mysql2&apos ...

What purpose does a private property serve within the interface?

Given the following code snippet: class X { bar() { return "bar" } constructor(private readonly x: number){} } interface Y extends X { } const f = (y: Y) => { console.log(y.bar()); } f({ bar: () => "tavern"}); The code does ...

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...

The module '@angular/cdk/clipboard' cannot be located at this time

I recently encountered an error after installing Angular Material in my project. Here is a snippet from my package.json file. I am using Angular 8 and have attempted to modify the versions of Angular Material components. "dependencies": { & ...

Error in TypeScript: It is not possible to use a component with MUI styling as a JSX element

I can't figure out what's going wrong. I'm attempting to include a child component in the main page, and I have a feeling it has something to do with MUI styles being applied at the end. I removed all unnecessary code and still encounter thi ...

Broaden material-ui component functionality with forwardRef and typescript

To enhance a material-ui component with typescript, I have the javascript code provided in this link. import Button from "@material-ui/core/Button"; const RegularButton = React.forwardRef((props, ref) => { return ( <B ...

Differences between the application/xml and text/xml MIME types

How can I receive an XML response from a servlet? The servlet returns a content type of "application/xml". When using XmlHttpRequest, I am able to get responseText, but not responseXml. Could this be related to the content type or the request type (I' ...

The 'React' namespace does not contain the exported members 'ConsumerProps' or 'ProviderProps'

Is it possible to install this library in Visual Studio with React version 15.0.35? Are there any other libraries that are compatible with this specific React version? import * as React from 'react'; import { RouteComponentProps, NavLink } from ...

Tips for properly defining path names in loadChildren for lazy loading in Angular 2 NgModules

When setting correct path names for loadChildren in the app-routing.module file within an Angular 2 NgModule, I encountered some issues. Despite following the NgModule concept outlined on the Angular main website, I still couldn't find clear informati ...

Tips for removing a row from a DataGrid column with the click of a button

I am facing a challenge with my data table that contains users. I am trying to implement a delete button for each row, but it seems like the traditional React approach may not work in this situation. Currently, I am utilizing the DataGrid component in the ...

Angular with Leaflet and Leaflet AwesomeMarkers error: "Attempting to access 'icon' property of undefined"

I'm attempting to integrate Leaflet Awesome Markers into my Angular 10 project to incorporate Font Awesome icons in my Leaflet markers. However, I'm running into an error when trying to create a L.AwesomeMarker. https://i.sstatic.net/7o81y.png ...

Ensuring Consistency of Values Between Child and Parent Components

Is there a way to ensure that the value of submitted in the child component always matches the value of submitted in the parent component? Appreciate any help! @Component({ selector: 'child-cmp', template: ` child:{{submitted}} ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

Angular: Maximizing Output by Extracting Data from Outer and Inner Observables using RxJS

Subscribing to queryParams gives me the item code, but how can I retrieve data from both getItemDetails and getSecuredData at the same time? To avoid using multiple subscribe() functions, I have opted for the mergeMap operator. this.route.queryParams.pip ...

What steps do I need to take to update Oceania to Australia on Google Maps?

While incorporating the Google Maps API into Angular, an issue arises when zooming out completely: https://i.stack.imgur.com/oZRut.png The label is displaying "Oceania" instead of "Australia". Is there a feasible method to modify this discrepancy? ...

Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example. I'm uncertain about how to resolve it. Your assistance would be greatly appreciated. type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; typ ...

Retrieving HTML Source Code in Android Studio

I am having trouble with testing this function even though the permissions are correctly set in the manifest file. Can anyone help me figure out what I'm doing wrong? public void fetchHTMLContent() throws Exception { URL url = new URL("http:/ ...

Dealing with nullable objects in Typescript: Best practices

Looking for a solution to have a function return an object or null. This is how I am currently addressing it: export interface MyObject { id: string } function test(id) : MyObject | null { if (!id) { return null; } return { ...

Unlocking the full potential of Bootstrap with the colspan feature

I'm currently in the process of developing an Angular 2 and Bootstrap application. Here's a snippet of my code: <div class="panel-body"> <table class="table table-striped table-bordered" style="width:100%;"> < ...