Maks K
Maks K

Reputation: 3914

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;
        });
}

Upvotes: 1

Views: 45

Answers (3)

martin
martin

Reputation: 96909

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;
    });
}

Upvotes: 2

Daniel Segura Pérez
Daniel Segura Pérez

Reputation: 1117

try:

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

        //get data with the URL
        return this.http.get(data)
            .map(r => {
                //Get something with data obtained with the URL
                return obj;
              });
        });
      }

Upvotes: 0

user4799206
user4799206

Reputation:

this.service.getData().subscribe((data: any) => {
  // data was setted here
  return this.http.get(data)
  .map(r => {

    return r;
  });
});

or

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

Upvotes: 0

Related Questions