返回修改后的可观察值Angular 6

时间:2018-10-05 15:03:55

标签: angular typescript observable

考虑以下示例:

 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 => {

    });


  }

这里我要实现的是封装从httpClient接收的数据并返回它,但这是在httpClient执行完成之后完成的。编译器告诉我“声明的类型既不是'void'也不是'any'的函数必须返回值”,这是正确的。我的问题是,当父级Observable必须等待httpClient.post()Observable完成任务时,如何解决此类问题?

1 个答案:

答案 0 :(得分:1)

使用map operator修改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;
    })
  );
}