Sampath
Sampath

Reputation: 65860

Return Observable inside the Promise

Could you tell me how can I return Observable here? I have tried many ways. But no success yet.

[ts] A function whose declared type is neither 'void' nor 'any' must return a value.

  deleteInvite(inviteId):Observable<HttpResponse<Object>> {
    this.getHttpHeader().then(headers => {
      return this.http.post(this.apiURL + "/deleteInvite", inviteId, { observe: "response", headers: headers })
    }).catch(err => {
      console.error(err);
    });
  }

  async getHttpHeader() {
    const accessToken = await this.getJWTToken();
    let headers = new HttpHeaders().set('Authorization', `Bearer ${accessToken}`);
    return headers;
  }

Upvotes: 6

Views: 6807

Answers (2)

Suraj Rao
Suraj Rao

Reputation: 29614

FOR rxjs version: 6.0.0 onwards

import { from } from 'rxjs';

 deleteInvite(inviteId):Observable<HttpResponse<Object>> {
    return from(this.getHttpHeader()).pipe(
        switchMap(headers => {
            return this.http.post(this.apiURL + "/deleteInvite", inviteId, { observe: "response", headers: headers })
        }),
        catchError(err => {
            console.error(err);
        })
    );
}

For older versions of rxjs:

Convert the thisGetHeaders() to an Observable by using fromPromise

import { fromPromise } from 'rxjs/observable/fromPromise';


deleteInvite(inviteId):Observable<HttpResponse<Object>> {
    return fromPromise(this.getHttpHeader()).pipe(
        switchMap(headers => {
            return this.http.post(this.apiURL + "/deleteInvite", inviteId, { observe: "response", headers: headers })
        }),
        catchError(err => {
            console.error(err);
        })
    );
}

Upvotes: 12

Romain Deneau
Romain Deneau

Reputation: 3061

getHttpHeader() returns a Promise. Just wait for it to unwrap its value. Then return the result of this.http.post which is the expected Observable. For that, use the await keyword inside a try/catch block:

async deleteInvite(inviteId) {
    try {
        const headers = await this.getHttpHeader();
        return this.http.post(this.apiURL + "/deleteInvite", inviteId, { observe: "response", headers: headers });
    }
    catch (err) {
        console.error(err);
    }
}

Then do await deleteInvite(inviteId) on the consumer side to handle the returned Promise.

Still, mixing Observable and Promise are complicated. Do all with Promises (or all Observables) can be easier : "return await this.http.post().toPromise()".

Upvotes: 0

Related Questions