2017-08-22 3 views
0

beendet hat habe ich eine Funktion in einem Dienst wie diese (Newel):RXJS erneut auszuführen beobachtbaren nach ersten

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() ein Objekt erstellt und schiebt es zu einer array.I wollen diese Funktion in einer anderen Komponente laufen, wenn es beginnt, ich meine so etwas wie dies für async willen

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

So tun kann alabels.component sieht so aus, scheint aber nicht zu dem Zeitpunkt fertig zu sein, an dem der nächste beginnt. Wenn ich das gedrückte Array protokolliere, bekomme ich das zweite Element wiederholt. Meine Vermutung ist, dass die zweite Funktion aufgerufen wird, bevor zuerst ein Wert zurückgegeben wird.

AlbenKomponente.

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; 

         } 
        ) 
       } 
      ) 
     } 
    ); 
} 

Jede Idee, wie Sie die Funktionen, um sicherzustellen, werden für die nächste zu beginnen laufen?

+0

hier, um diese Antwort Siehe: https://stackoverflow.com/a/45737338/1791913 – Faisal

+0

Same als https://stackoverflow.com/questions/30519645/how-can-i-make-on-rxjs-observable-sequence-wait-for-another-to-complete-before? –

Antwort

Verwandte Themen