从 HttpModule 中的 RxJS observable 中检索数据

ran*_*its 2 observable rxjs axios nestjs

我无法理解如何mapHttpServiceNestJS 应用程序中取出数据属性。据我了解,这Observable只是包装axios. 下面是一些示例代码:

interface Todo {
   task: string,
   completed: false
}

import {
  Injectable,
  HttpService,
  Logger,
  NotFoundException,
} from '@nestjs/common'
import { map } from 'rxjs/operators

async getTodo(todoUrl: string): Todo {
   const resp = this.httpService
      .get('https://example.com/todo_json')
      .pipe(map(response => response.data)) // map task/completed properties?
   return resp
}
Run Code Online (Sandbox Code Playgroud)

resp在这种情况下似乎是类型Observable。如何仅检索我想map在此请求中使用的数据属性以返回我的Todo界面?

Jay*_*iel 5

默认情况下,Nest 会为您订阅 observable,您可以从服务中返回 Observable。在这种情况下,您可以执行以下操作

@Injectable()
export class TodoService {

  constructor(private readonly http: HttpService) {}

  getTodos(todoUrl: string): Observable<Todo> {
    return this.http.get(todoUrl).pipe(
      map(resp => resp.data),
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

只要你有一个控制器类调用this.todoSerivce.getTodos(todoUrl)并返回它,响应就会被发送出去。

但是,如果你想将它变成一个 promise,因为你更习惯它们,你可以.toPromise()在 observable 链上添加一个方法,现在它是可等待的(尽管它会更慢,因为它必须等待 observable 发出它的完整事件)。

示例.toPromise()

@Injectable()
export class TodoService {

  constructor(private readonly http: HttpService) {}

  getTodos(todoUrl: string): Todo {
    const myTodo = await this.http.get(todoUrl).pipe(
      map(resp => resp.data),
    ).toPromise();
    return myTodo;
  }

}
Run Code Online (Sandbox Code Playgroud)

  • @jim `从'rxjs/operators'导入{map}` (3认同)