我遇到了一些麻煩,使得嵌套的Observable調用。我的意思是調用一個http服務來檢索一個用戶,然後從用戶那裏獲取id來進行另一個http調用,最後在屏幕上顯示結果。如何在Angular2中嵌套Observable調用
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())
請建議其最好的工作方法定義一個Observable鏈。
「這段代碼的作品,但似乎是錯誤的做法,我...」爲什麼? –