【发布时间】:2017-03-15 12:36:53
【问题描述】:
我正在尝试在我的 Angular 2 应用程序中实现两个连续的 HTTP 请求。 当用户单击登录按钮时,我想将刷新和访问令牌保存在 LocalStorage 中,然后再执行一个 HTTP 请求以获取用户信息。我看到了这篇文章,但它在我的情况下不起作用。 Angular 2 - Chaining http requests
这是我对登录和 getMe 服务的初始实现: 如何合并下面的请求?
login.component.ts
this.authenticationService.login(this.user.email, this.user.password)
.subscribe(
data => {
// this.alertService.success('Registration successful', false);
this.router.navigate([this.returnUrl]);
},
error => {
console.log(error);
this.alertService.error(error);
this.loading = false;
});
authentication.service.ts
login(email: string, password: string) {
let headers = new Headers({
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Cache-Control': 'no-cache'
});
let options = new RequestOptions({ headers: headers });
return this.http.post(this.config.apiUrl + this.authenticationUrl + '/login',
JSON.stringify({ email: email, password: password }), options)
.map((response: Response) => {
let tokens = response.json();
if (tokens && tokens.token && tokens.refreshToken) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('tokens', JSON.stringify(tokens));
}
});
}
user.service.ts
getMe() {
console.log('getMe');
return this.http.get(this.config.apiUrl + this.usersUrl + '/me', this.jwt()).map((response: Response) => {
let user = response.json();
if (user)
localStorage.setItem('currentUser', JSON.stringify(user));
});
}
【问题讨论】:
-
首先,您的函数可以返回一个承诺或回调(例如 Promise
)。如果你使用 Promise,你可以用 (.then, .catch) 链接结果。如果你传递一个回调,你可以通过回调链接方法。 -
我觉得如果你使用 Observable 或者 flatMap 可以避免这种情况。
标签: javascript angular httprequest rxjs