Steven
Steven

Reputation: 81

How to transform and project array elements from http backend in angular7

From the http backend I get an observable with a list of users:

Observable<User[]>

User is defined as:

export interface User {
  id:number;
  username:string;
}

I am using angular 7. In the end as the result of the backend call I want to have an array of the user ids?

What is the best and RXJS-like way to perform this transition?

Upvotes: 0

Views: 62

Answers (4)

webdevius
webdevius

Reputation: 811

In your service:

import {Injectable} from '@angular/core';
import {Http} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable()
class MyService {
  constructor(private http: Http) {}

  getUsers(): Observable<User[]> {
    return this.http.get('http://my-api.com/users')
  }
}

In your component:

import {map} from 'rxjs/operators';

@Component({ /* ... * / })
export class MyComponent implements OnInit {
  userIds$: Observable<number[]>;

  constructor(private myService: MyService) {}

  ngOnInit() {
    this.userIds$ = this.myService.getUsers().pipe(
      map(users => users.map(user => user.id))
    )

    // Now whether you directly subscribe to `this.userIds$` or use the `async` pipe.
    // The Result will be an array of numbers (user ids)
  }
}

Learn More about Array map method and RxJS map operator. You will use these a lot.

Upvotes: 2

Ashok
Ashok

Reputation: 753

you can use .map() function to achieve this. Below is the example of how you can do this:

var userIds= Users.map(function(user) {
  return user.id
});

Upvotes: 0

Igor
Igor

Reputation: 62213

Using your defined interface and that the http call returns an array that conforms to that interface you would do it like this. The conversion between the returned type to the expected type (User interface to number in this case) can be done with map.

userService.ts

export class UserService {
  constructor(private readonly http: HttpClient) {}

  getUsers() : Observable<User[]> {
    return this.http.get<User[]>('/some/url');
  }
}

userComponent.ts

export class UserComponent implements OnInit {

  userIds: number[];
  constructor(private readonly service: UserService) {}

  ngOnInit() {
    this.service.getUsers().subscribe(users => this.userIds = users.map(_ => _.id));
  }
}

Upvotes: 1

Tobin
Tobin

Reputation: 2018

Making it super verbose :)

this.userIds = []
observable.subscribe(users => {
 this.userIds = users.map(user => user.id)
})
  • Subscribe to the 'result' of the API call
  • observable will present you with array of Users
  • Map function applies function to each element of array and returns, in this case, the user.id
  • Assign this result to our userIds array

Upvotes: 0

Related Questions