1

I have a function in a service like this (newEL):

songs.service.ts

import {Injectable, Inject} from '@angular/core';
import {HttpModule, Headers, Http, Response } from '@angular/http';
import 'rxjs/Rx';

export class SongsService {

newAlbum(name:string){
  name = name.replace(/ /g, '+');
  var albumID= '';
  return this.http.
  get(uri + name)
  .map(
    ( res:Response) => {    
        var rawData = res.json();       
        // console.log(rawData);
        var albumName:string = rawData.data[0].title;
        albumID = rawData.data[0].id;
        this.albumSongs(albumID).subscribe(
            songs => {
            this.newSongs = songs
            this.albumData = {
                name:this.newAlbumName,
                songs:this.newSongs
            };
            this.testalbums.push(this.albumData);
            }
        );

        // this.albums.push(albumName,this.albumSongs(albumID))
    return [albumName, albumID]
    }
    );
   }

  newEL (albumName){
   return this.newAlbum(albumName)
    .map(
        album => {
           return this.newAlbumName = album[0];
        }
    );
  }
}

newEL() creates an object and pushes it to an array.I want to run this function in another component when it starts,I can't do something like this for async sake

ngOnInit(){
  this.songsService.newEl("sams town");
  this.songsService.newEl("Blink182");
  this.songsService.newEl("enema of the");
}

So my albums.component looks like this, but doesn't seem to finish first by the time the next one starts. When I log the array pushed I get the second element repeated. My guess is second function is called before first one returns a value.

AlbumsComponent.

export class AlbumsComponent {
    ngOnInit() {
      this.songsService.newEl("sams town").subscribe(
        album => 
            this.songsService.newEl("Madona").subscribe(
                album => { 
                    this.songsService.newEl("enema of the").subscribe(
                        album => { 
                            this.albums = this.songsService.testalbums; 
                            console.log(this.albums)
                            // return this.albums = this.songsService.testalbums;   

                        }
                    )
                }
            )
        }
    );
}

Any idea on how to ensure the functions are run for the next one to begin?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Jaime FH
  • 39
  • 1
  • 10

1 Answers1

0

You can use forkJoin or switchMap to create a dependency between the Observables used in angular service . Otherwise you can create a chain of promise with dependency in a primitive way .

see the link below

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/forkjoin.md

and this answer too

handling observables when one is dependent on data from another

Niladri
  • 5,832
  • 2
  • 23
  • 41