3
\$\begingroup\$

Here is my code with 2 services, one is messageService which is used to get user messages:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import 'rxjs/add/operator/retry';
import 'rxjs/add/operator/catch';
import { handleError } from '../common/error-handler';


@Injectable({
  providedIn: 'root'
})
export class MessagesService {
  private _config = environment;

  constructor(private http: HttpClient) { }

  getMessages() {
    return this.http.get(`${this._config.apiUrl}/messages`)
      .retry(3)
      .map(data => (data && data['messages']) || [])
      .catch(handleError);
  }

}

And the other is usersService which is used to get user information based on user_id:

import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Injectable } from '@angular/core';
import { handleError } from '../common/error-handler';

@Injectable({
  providedIn: 'root'
})
export class UsersService {
  private _config = environment;

  constructor(private http: HttpClient) { }

  getUser(user_id) {
    return this.http.get(`${this._config.apiUrl}/users/${user_id}/public_profile`)
      .retry(3)
      .map(data => data || {})
      .catch(handleError);
  }
}

And in the constructor of my component:

    @Component({
      selector: 'wall',
      templateUrl: './wall.component.html',
      styleUrls: ['./wall.component.css']
    })
    export class WallComponent {

      constructor(private messageService: MessagesService, 
                  private usersService: UsersService) {

        this.messageService.getMessages()
              .switchMap(response => {
                let resArray: any[] = response.map(
                  post => {
                    return Observable.zip(
                      this.usersService.getUser(post.user_id),
                      Observable.of(post)
                    );
                  });
                  return Observable.merge(...resArray)
              }).switchMap(res => {
                res[1]['user'] = res[0];
                this.messages.push(res[1]);
                return Observable.of(res[1]);
              })
              .subscribe(final_post => {
                console.log('final post:', final_post)
              })
        }
    }

The question is how should I get user messages using Observable and then getting users information for each message (each message may have different user information), then merging them into one object which finally will be used in the desired component with fewer Observable pipelines? I suppose using merge and then again switchMap to merge these data is not optimal and best practice.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.