Validating multiple conditions in Typescript by passing them as function parameters

As a beginner in TS/JS, I am looking to validate multiple conditions passed as arguments to a function. For instance, currently I am verifying the user role name, but in the future, I may need to check other conditions.

  validateUserDetails(): Promise<Boolean> {
    return new Promise<Boolean>((resolve, reject) => {
      this.currentLoggedInUserRole = this.sharedService.getCurrentUser()['roleName'];
      if (this.currentLoggedInUserRole) {
        let url = `<some GET url>`;
        this.http
          .get<any>(url)
          .pipe(
            take(1),
            catchError((error) => {
              reject(false);
              return throwError(error);
            })
          )
          .subscribe((response: any) => {
            if (
              response.length > 0 && response.some((user) => user['roleName'] === this.currentLoggedInUserRole)) {
              resolve(true);
            } else {
              resolve(false)
            }
          });
      }
    });
  }
this.userValidationService.validateUserDetails().then(isUserValid => {
  //some logic
}).catch((error) => {console.log(new Error(error))})

I aim to pass conditions to be checked as arguments to the function like below, perhaps using arrays or maps rather than comma separated values.

this.userValidationService.validateUserDetails(['userRole', userID])
.

this.userValidationService.validateUserDetails('userRole').then(isUserValid => {
  //some logic
}).catch((error) => {console.log(new Error(error))})

My question is how can I pass arguments with multiple conditions and, how can I handle them inside my promise to validate all/partial conditions. If we have ['userRole', 'userID', 'clientID'], and userRole returns true, userID returns false, and clientID returns true, the consolidated result should be false - meaning if any one condition fails, the result should be false. How can this be achieved using rxjs forkJoin()?

Thank you.

Answer №1

If you are searching for information on TypeScript and Rest Parameters, check out this helpful tutorial: TypeScript - Rest Parameters

validateUserDetails(...fields: string[]): Promise<Boolean> {
  ...
}

You have the option to pass the function's parameters individually (separated by commas) or as an array, and the result will remain the same.

this.userValidationService.validateUserDetails(['userRole', 'userID', ...])

or

this.userValidationService.validateUserDetails('userRole', 'userID', ...)

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

Attempting to retrieve currentScript is causing a typeError to be thrown

I'm attempting to access a custom attribute that I added to my script tag: <script type="text/javascript" src="https://.../mysource.js" customdata="some_value"></script> To make this work on Internet Explorer ...

By harnessing a JSON response

After sending an ajax request, the server's response is as follows: {"error":false,"success":true} The ajax code used: $.ajax({ url: '/update', type: 'post', data: $(this).serialize(), success: function(response) ...

Angular Tutorial: Modifying the CSS transform property of HTML elements within a component directly

Currently, I'm in the process of developing an analog clock for a project using Angular. My challenge is figuring out how to dynamically update the sec/min/hour handlers on the clock based on the current time by manipulating the style.transform prope ...

How can I stop the li item from swiping right in JQuery mobile?

I've been implementing this code from https://github.com/ksloan/jquery-mobile-swipe-list and I've made some modifications to it. It's been working well for me so far. However, the code includes two buttons - one on the right and one on the l ...

Is there a way to incorporate a Laravel foreach loop within a JavaScript file?

I recently added a select-box using jQuery: <span onclick="createProduct()">Add New<i class="fa fa-plus"></i></span> <script> function createProduct() { var html = ''; html += ' <div clas ...

ng-include failing to retrieve file name containing UTF-8 character

I encountered an issue with the ng-include directive in the code snippet below. The file name it's trying to access contains a special character, specifically an ñ, resulting in a not found error being displayed. <div ng-include="'{{mainCtrl ...

The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be corre ...

"Failure encountered while trying to fetch JSON with an AJAX request

I am facing an issue with an ajax request. When I make the request with the property dataType: 'json', I get a parsererror in response. My PHP function returns the data using json_encode(), can someone assist me? On the other hand, when I make th ...

Displaying selected values in a Multi Select Listbox upon submission of the same form when an error occurs

When the page is first loaded: Retrieve the values from the table field and store them in a variable If the field is blank, do not take any action Populate the listbox with default custom values When the form is submitted (on the same page) and multipl ...

What is the best method for converting a plist file into a json file?

Is there a way to convert an existing plist file into a JSON file using one of the following programming languages: JavaScript, Java, Objective-C, Python, or Ruby? Any suggestions on how to do this? ...

"Discover the power of Algolia's docSearch feature

Currently, I am working on integrating Algolia DocSearch into my docusaurus project. After obtaining the api key and api id from Algolia, I am unsure of the next steps to take. I would appreciate guidance on the necessary procedures that need to be followe ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

I encountered an ECONNREFUSED error while attempting to fetch data from a URL using NodeJS on my company-issued computer while connected to the company network. Strangely

After searching through forums and conducting extensive Google searches, I have come across a problem that seems unique to me. No one else has posted about the exact same issue as far as I can tell. The issue at hand is that I am able to successfully make ...

Angular, Transforming JSON with RxJS Operators in TypeScript

Upon receiving the JSON object (Survey) from the server, it looked like this: { "id": 870, "title": "test survey", "questions": [ { "id": 871, "data": ...

Gather information from every user and display their user ID in an HTML table, allowing for updates through a button

Can anyone help me create a table like the one shown here: https://i.sstatic.net/Hj4T9.png The table should fetch data from my firebase database. Here is the structure of my requests database: https://i.sstatic.net/0lJGa.png. I've been trying to mo ...

What is the best way to identify and list distinct values within a MongoDB collection when the values are arrays of objects?

Is there a way to extract unique values from a collection that consists of an array of objects? While the distinct method works for strings and numbers, I'm facing a situation where the values are objects. Here's a simplified version of the mode ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

The Kendo Angular UI Gauges automatically adjust their size after being updated

Currently, I am utilizing the RadialGauge component from Kendo UI with angular. I am dynamically loading data for the gauges via an API using rxjs every 3 minutes. Below is a snippet of my code: interval(2e5) .pipe( startWith(() => forkJoin( ...

Automatically reconstructing local packages when changes occur

After installing a local package using npm local paths, I am looking for a way to automatically rebuild or re-install the package whenever I make changes to the file. Can anyone help me with this? I have searched online extensively but haven't come a ...

Why are the links in the navgoco slide menu failing to function properly?

I utilized a demo from jQueryRain to create a collapsible menu using jQuery. However, after completion, I discovered that none of the links were functioning properly. Upon visiting the documentation page, I noticed that many users were encountering the sam ...