http toPromise返回对象

时间:2019-02-01 21:41:01

标签: javascript angular typescript promise rxjs

我具有以下功能:

getUser(userId: string) : Observable<any> {
    var getUserURL = `/api/users/${userId}`,
        getUserStatus = this.getUserStatus();


    return this.http.get<any>(getUserURL).pipe(
      catchError(this.handleError('getUser - Get User failed', null))
    );
  }

这会从REST API对该URL /api/users/${userId}的响应中返回数据到toPromise

有什么方法可以返回包含来自REST API的响应数据的对象+本地数据(getUserStatus),在这种情况下为布尔值。 谢谢

2 个答案:

答案 0 :(得分:2)

您的请求不会返回Promise,除非您的示例中未包含该请求。你有一个可观察的。

假设我正确理解了您的问题。如果要返回HTTP响应+本地状态,则可以使用管道运算符执行以下操作:

服务

getUser(userId: string) : Observable<any> {
  const path = `/api/users/${userId}`
  const userStatus = this.getUserStatus();

  return this.http.get<any>(path)
    .pipe(
      map((response: any) => {
        return { response, userStatus };
      }),
      catchError(this.handleError('[USER]::getUser Failed', null))
    );
}

组件

this.getUser(1000).subscribe(({response, userStatus}) => { 
  // Handle response and status
  console.log('RESPONSE', response);
  console.log('USER_STATUS', userStatus);
});

答案 1 :(得分:1)

就像@mtputlz一样,您正在返回一个Observable。如果您想返回您的答复,在您的情况下为布尔值。然后我们可以将可观察者转换为一个承诺:

def index(request):
    today = timezone.now()
    week_ago = today - timedelta(7)

    ma_w_dates = MemberAction.objects.filter(datetime__date__gte=week_ago,datetime__date__lte=today)
    mention_pts = Sum('membermention__points', filter=Q(membermention__date__date__gte=week_ago,membermention__date__date__lte=today))
    action_pts = Sum('memberaction__points', filter=Q(memberaction__datetime__date__gte=week_ago,memberaction__datetime__date__lte=today))
    members = Member.objects.annotate(points_actions=action_pts).annotate(points_news=mention_pts).order_by('-points_actions').prefetch_related(Prefetch('memberaction_set', queryset=ma_w_dates))[:5]

    context = {'members':members}
    return render(request, 'data/index__text.html', context)