问题
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