我在进行嵌套的 Observable 调用时遇到了一些麻烦。我的意思是调用一个 http 服务来检索用户,然后从用户处获取 id 以进行另一个 http 调用,最后在屏幕上呈现结果。
1) HTTP GET 1 : 获取用户
2) HTTP GET 2:通过唯一标识符作为参数来获取用户的偏好
这将转换为组件中的以下代码Blah.ts
:
版本1- 此代码不显示任何内容
ngOnInit() {
this.userService.getUser()
.flatMap(u => {
this.user = u; // save the user
return Observable.of(u); // pass on the Observable
})
.flatMap(u => this.userService.getPreferences(this.user.username)) // get the preferences for this user
.map(p => {
this.preferences = p; // save the preferences
});
}
版本2- 这段代码有效,但对我来说似乎是错误的方法:
this.userService.getUser().subscribe(u => {
this.user = u;
this.userService.getPreferences(this.user.username).subscribe(prefs => {
this.preferences = prefs;
});
});
这是模板:
<h3>User</h3>
<div class="row col-md-12">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">User details</h3>
</div>
<div class="panel-body">
<table class="table table-condensed">
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
<th>Enabled</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{user?.username}}</td>
<td>{{user?.fullName}}</td>
<td>{{user?.enabled}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- end of col 1-->
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">User preferences</h3>
</div>
<div class="panel-body">
<table class="table table-condensed">
<thead>
<tr>
<th>Language</th>
<th>Locale</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{preferences?.preferences?.get('language')}}</td>
<td>{{preferences?.preferences?.get('locale')}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- end of col 2-->
</div>
<!-- end of row 1-->
我认为展示服务没有任何意义,这只会让http get()
调用如下:
http.get('http://blablah/users/')
.map((response) => response.json())
请建议哪种方法是定义可观察量链的最佳工作方法。
您应该稍微阅读一下 rxjs 的运算符。你的例子非常冗长并且使用flatMap
and map
在某种程度上,它们不应该被使用。另外,您的第一个示例无法工作,因为您没有订阅 Observable。
这将满足您的需要:
ngOnInit() {
this.userService.getUser().pipe(
tap(u => this.user = u),
flatMap(u => this.userService.getPreferences(u.username))
).subscribe(p => this.preferences = p);
}
legacy:
在 5.5 版本之前,rxjs 专门使用基于原型的运算符。
此代码在功能上等同于上面的代码:
ngOnInit() {
this.userService.getUser()
.do(u => this.user = u) //.do just invokes the function. does not manipulate the stream, return value is ignored.
.flatMap(u => this.userService.getPreferences(u.username))
.subscribe(p => this.preferences = p);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)