Search code examples
angulartypescriptrxjssubscription

How to return data after stream was subscribed?


How to return data after the stream was subscribed? For example, I get URL in subscription, and then I want to return the stream with data based on this URD

public get() {
    this.service.getData().subscribe((data: any) => {
        // data was setted here
        this.url = data;
    });

    return this.http.get(this.url)
        .map(r => {
            ...
            return obj;
        });
}

Solution

  • You should use concatMap (or mergeMap) for this and turn this into a chain:

    public get() {
      this.service.getData().do((data: any) => {
          // data was set here
          this.url = data;
        })
       .concatMap(data => this.http.get(data))
       .map(r => {
         ...
         return obj;
        });
    }
    

    Or maybe you don't even need to be using this.url (I don't know what's your use-case).

    public get() {
      this.service.getData()
       .concatMap(url => this.http.get(url))
       .map(r => {
         ...
         return obj;
        });
    }