首页 > 解决方案 > Angular RxJs - 获取订阅者而不是所需的值

问题描述

在获得当前客户订单之前,我需要返回他的姓名,因此我的相关服务类部分如下所示:

更新:

export class AuthService {

      customerNameUrl = 'customers/name/' + name;
      . . . 
      getCustomerOrders(customerName: string): Observable<CustomerOrder[]> {
          let currentCustomerName = this.getCurrentCustomer(customerName).subscribe(customer => customer.name);
          console.log(currentCustomerName);     <--- Error
          let customerOrders =  this.http.get<CustomerOrder[]>(this.customerOrdersUrl);
          console.log(customerOrders);
          return customerOrders
      }

      getCurrentCustomer(name: string): Observable<Customer> {
        const url = this.customerNameUrl;
        return this.http.get<Customer>(url).pipe(
          tap(_ => this.log(`fetched customer name=${name}`, 'success')),
          catchError(this.handleError<Customer>(`getCustomer name=${name}`))
        );
      }
      . . .
}

但是第一个 console.log 显示的是订阅者而不是所需的值。我试图添加地图运算符以仅从实体中获取名称但没有成功,可能是以错误的方式添加它,知道吗?

标签: angulartypescriptrxjs

解决方案


该方法subscribe返回一个Subscriber. 这是有道理的吧?整体Observable和JS本质上,主要是异步的。您异步获取数据,您应该以某种方式等待它,并使用回调继续返回的数据。有关此的主线程,请参见此处

在您的情况下,这意味着您将不得不使用某些东西来制作Observables链条。好在有一堆运算符,我们必须有一个可以使用。在这种情况下,最好的运算符是mergeMapor concatMap。但是,我不清楚为什么需要客户姓名,因为您没有将其传递给获取客户 API。不过,这能解决您的疑问吗?

getCustomerOrders(customerName: string): Observable<CustomerOrder[]> {
  return this.getCurrentCustomer(customerName).pipe(
    // here you have your customer object, but what do you want to do with it?
    mergeMap((customer) => this.http.get<CustomerOrder[]>(this.customerOrdersUrl))
  );
}

getCurrentCustomer(name: string): Observable<Customer> {
  const url = this.customerNameUrl;

  return this.http.get<Customer>(url).pipe(
    tap(_ => this.log(`fetched customer name=${name}`, 'success')),
    catchError(this.handleError<Customer>(`getCustomer name=${name}`))
  );
}

推荐阅读