2

I have an enumeration in my typescript code, which lists all possible user roles:

enum UserRole {
    CONSULTANT,
    MANAGER,
    ...
}

And I have a REST endpoint /users/id/roles that returns array of strings representing roles of a particular user:

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

Now I want to map this array in my frontend code. I tied doing it like this:

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()));
}

But I get:

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 any way to convert string-array to array of enum elements?

Note: Im using Typescript 2.5.3. in pair with Angular 5.0.5.

1 Answer 1

4

You can use map on the array returned from your server, once you've converted it to an object using json, like so:

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

In case you get a Typescript error, you might need to cast the json result first, like so:

return this.http.get(`/users/${id}/roles`)
    .map(response => (<string[]>response.json()).map(x => UserRole[x]));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.