Sam*_*i-L 0 rxjs typescript angular
在获取当前客户订单之前,我需要返回他的姓名,因此我的相关服务类部分如下所示:
更新:
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}`))
);
}
. . .
}
Run Code Online (Sandbox Code Playgroud)
但是第一个 console.log 显示的是订阅者而不是所需的值。我试图添加 map 运算符以仅从实体中获取名称但没有成功,可能以错误的方式添加它,知道吗?
该方法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}`))
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |