angular - 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 显示的是订阅者而不是所需的值。我试图添加地图运算符以仅从实体中获取名称但没有成功,可能是以错误的方式添加它,知道吗?
解决方案
该方法subscribe
返回一个Subscriber
. 这是有道理的吧?整体Observable
和JS本质上,主要是异步的。您异步获取数据,您应该以某种方式等待它,并使用回调继续返回的数据。有关此的主线程,请参见此处。
在您的情况下,这意味着您将不得不使用某些东西来制作Observables
链条。好在有一堆运算符,我们必须有一个可以使用。在这种情况下,最好的运算符是mergeMap
or 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}`))
);
}
推荐阅读
- signature - Bro IDS signature_match 触发器
- javascript - 旋转包含的图像后,div 高度未正确设置
- angular - Angular,TypeError:无法读取 null 的属性“任务”
- java - 调用时如何处理其他模块自定义异常
- angular - Ionic 3 Angular 4 App 在产品发布版本上抛出错误
- php - 如何在 Yii2 urlManager 中为默认页面创建干净的 url
- javascript - JQuery 调用在我的 AngularJS 页面中不起作用
- c# - 无法在 C# 中使用集合初始化程序错误初始化十进制类型
- javascript - 如何查找数组是否有其他元素?
- sendgrid - 如何在 sendgrid node.js v3 客户端中将 pdf 文件作为附件发送