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?