SFernando
SFernando

Reputation: 1124

Waiting callback to finish observable

I have two observables in my service like this

return Observable.forkJoin(
   this.http.post(this.baseUrl, JSON.stringify(user), this.serverConfig.getJsonHeader()),
   this.awsService.uploadData(params)
)

and I subscribe them in my component

.subscribe(
    data => {
       console.log('data[0]',data[0]);
       console.log('data[1]',data[1]);
    }
);

and my uploadData function,

uploadData(params: any): Observable<any> {
      return Observable.of(
          this.getBucket().upload(params,
               (error, resp) => {
                  console.log('error', error);
                  console.log('resp', resp);
               }
           )
       )
   }

The problem is I was unable to run this callback function before subscription runs. It always runs after the subscription. What should I do to run callbacks before the subscription?

Upvotes: 0

Views: 7184

Answers (1)

SFernando
SFernando

Reputation: 1124

Finally I was able to fix this. I could have used promise instead of observable like this

uploadData(params: any) : Promise<any>{
        return new Promise((resolve, reject) => {
            this.getBucket().upload(params, (err, data) => {
                if (err)
                    reject(err);
                 else
                    resolve(data);
            });
        });
    }

and editing fork join like this

Observable.fromPromise(this.awsService.uploadData(params))

Upvotes: 1

Related Questions