Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code:

enum UserRole {
    CONSULTANT,
    MANAGER,
    ...
}

There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user:

[
    "CONSULTANT",
    "MANAGER",
    ...
]

Now, I need to map this array in my frontend application. I tried achieving this using the following method:

import {Http} from '@angular/http';
import {Observable} from "rxjs/Observable";
import {plainToClass} from "class-transformer";
...

getUserRoles(id: string): Observable<UserRole[]> {
    return this.http.get(`/users/${id}/roles`)
        .map(responce => plainToClass(UserRole, responce.json()));
}

However, I encountered the following error:

error TS2345: Argument of type 'typeof UserRole' is not assignable to parameter of type 'ClassType'. Type 'typeof UserRole' provides no match for the signature 'new (...args: any[]): UserRole[]'.

Q: Is there a workaround to convert a string array into an array of enum elements?

Note: My environment includes Typescript 2.5.3 and Angular 5.0.5.

Answer №1

One way to handle data received from your server is by using the map function on the array. First, you'll need to convert the response into an object with JSON formatting. Here's how you can achieve this:

return this.http.get(`/users/${id}/roles`)
    .map(response => response.json().map(x => UserRole[x]));
}

If you encounter a Typescript error when implementing this code, you may have to explicitly cast the result of the json method. See the example below:

return this.http.get(`/users/${id}/roles`)
    .map(response => (<string[]>response.json()).map(x => UserRole[x]));
}

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

Erasing a comment creates empty spaces

I've encountered an issue with my idea whiteboard where removing comments leaves unwanted blank spaces between ideas. For example, if I have the following comments: But when I delete something: Is there a way to ensure that no gaps are left between ...

Is it better to Vuex - manipulate store item twice, trigger new items, or perform transformations within components each time they are mounted?

I am considering performing two separate transformations on a single, large store item and then saving the results as two new store items. For instance: setEventsData: (state, data) => {...} // main huge master object // perform transformations on it an ...

Manipulating a React table: Customizing a row in the table

Below is the code snippet: const [data, setData] = useState([ {id: 1, name: 'paper', qty: 10}, {id: 2, name: 'bottle', qty: 10}, ]); const [isEditable, setEditable] = useState([]); useEffect(()=>{ data.map(each=>{ ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

Encountering the error message "undefined is not a function" while attempting to retrieve JSON data

I'm running into some issues with retrieving data from a PHP file. Upon calling the variable msg[0}, I'm getting an undefined error even though it should have been filled in during the JSON request. The JavaScript code is provided below, and you ...

Adding a JSON array to HTML using JavaScript

Looking to incorporate JSON Array data into an HTML list with Headings/Subheadings using JavaScript. I experimented with two methods - one involving jQuery and the other mostly vanilla JS. The initial attempt (link here: http://jsfiddle.net/myu3jwcn/6/) b ...

Utilizing Vue JS to set an active state in conjunction with a for loop

Currently in Vue, I have a collection of strings that I am displaying using the v-for directive within a "list-group" component from Bootstrap. My goal is to apply an "active" state when an item is clicked, but I am struggling to identify a specific item w ...

Issues with the initial calculator project I built using JavaScript (excluding HTML and CSS)

My first calculator is nearly complete, but I have encountered a challenge. The functionality of my calculator is quite simple; it prompts the user for input using window.prompt and performs addition, subtraction, multiplication, or division based on the u ...

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

Is it possible to encode JavaScript with masked binary values?

This segment of code produces the output D. The real question is - HOW? alert([][(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![] ...

Encountering a persistent Unhandled rejection Error while utilizing NodeJs with Bluebird library

Currently in the process of developing a daemon that listens to TCP connections, sends commands, and listens for events. I made the decision to utilize bluebird to eliminate callbacks, but I'm encountering an issue. I can't seem to catch a rejec ...

Steps for removing the bottom border for the last child in the Material UI Box Component

I have a Box Component where ListItems are wrapped. For each child, I have a border-bottom of 1px solid class set for the Box component, but I don't want it for the last child. How can I achieve that? {data.map((item, i) => { return ...

What is the best method for installing the most recent 1.1.5 version of is-callable?

After running the command npm install, an error occurred: npm ERR! code ETARGET npm ERR! notarget No matching version found for is-callable@^1.1.5. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

Issues discovered with using Typescript in Visual Studio 2015

I'm having trouble figuring out the issue. Right now, the typescript file is not appearing correctly in Visual Studio 2015. Take a look at the image linked here: https://i.stack.imgur.com/oXXWD.png ...

Trouble encountered during installation of Angular CLI: module.js - code 549

I recently encountered issues with Angular-CLI, so I decided to update it using the command $ npm install -g @angular/cli. However, after doing so, I am facing a new error message. Can anyone provide assistance with this problem? module.js:549 throw err ...

Discovering the version of the Javascript library utilized on a website - a step-by-step guide

My quest is to uncover the versions of JavaScript libraries being utilized by popular websites. By using phantomjs.exe, I successfully identified the version information for jquery. However, I am currently at a loss on how to expand this capability to inc ...

Tips for implementing JWT in a Node.js-based proxy server:

I am a Node.js beginner with a newbie question. I'm not sure if this is the right place to ask, but I need ideas from this community. Here's what I'm trying to do: Server Configurations: Node.js - 4.0.0 Hapi.js - 10.0.0 Redis Scenario: ...