Angular RxJs - Getting subscriber instead of the required value

天大地大妈咪最大 提交于 2020-03-26 01:39:11

问题


Prior to getting the current customer orders I need to return his name, so my related Service class part looks like the following:

Updated:

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}`))
        );
      }
      . . .
}

But the first console.log shows subscribers instead of the required value. I have tried to add map operator to get only the name from the entity but didn't succeed, maybe added it in the wrong way, any idea?


回答1:


The method subscribe returns a Subscriber. That makes sense right? The whole Observable and JS by nature, is mainly async. You fetch data async and you should somehow wait for it, and use a callback to continue with the returned data. See here for the main thread about this.

In your case that would mean that you will have to use something to make the Observables chain. Good thing there are a bunch of operators, there must be one we can use. In this case, the best operator would be mergeMap or concatMap. However, it's unclear to me why you would need the name of the customer, as you are not passing that to the get customer API. Nevertheless, does this solve your query?

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}`))
  );
}


来源:https://stackoverflow.com/questions/60465057/angular-rxjs-getting-subscriber-instead-of-the-required-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!