1
votes

Consider the following example:

 login(context: LoginContext): Observable<Credentials> {

    let credentials = JSON.stringify(context);

    this.httpClient.post("http://localhost:64636/api/Account/login", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    }).subscribe(response => {
      let token = (<any>response).token;

      const data = {
        username: context.username,
        token: token
      };

      this.setCredentials(data, context.remember);
      return of(data);

    }, err => {

    });


  }

Here what I am trying to achieve is to encapsulate the data that is received from the httpClient and return it, but this is done after the execution of httpClient is complete. The compiler tells me that "a function whose declared type is neither 'void' nor 'any' must return a value" and rightfully so. My question is, how to resolve such issue when the parent observable must wait for the httpClient.post() observable to finish its task?

1
Have you tried putting a return before the this.httpClient.post... and subscribing to login ? - Jacopo Sciampi
Yes that would work but the thing is, I want to do the work of encapsulating this received data within the login function and then return it. - astralmaster

1 Answers

1
votes

Use the map operator to modify the value returned by an Observable:

login(context: LoginContext): Observable<Credentials> {

  let credentials = JSON.stringify(context);

  return this.httpClient.post("http://localhost:64636/api/Account/login", credentials, {
    headers: new HttpHeaders({
      "Content-Type": "application/json"
    })
  }).pipe(
    map(response => {
      let token = (<any>response).token;
      const data = {
        username: context.username,
        token: token
      };
      this.setCredentials(data, context.remember);
      return data;
    })
  );
}