【问题标题】:Angular 2 - Sequential HTTP requestsAngular 2 - 顺序 HTTP 请求
【发布时间】: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));
    });
}

【问题讨论】:

标签: javascript angular httprequest rxjs


【解决方案1】:

您在登录方法上返回一个 Observable,因此在您的数据订阅中,只需从您的用户服务中调用 getMe()。

this.authenticationService.login(this.user.email, this.user.password)
    .subscribe(
    data => {
        // Check to make sure data is what you expected, then call getMe()
        this.userService.getMe();
        this.router.navigate([this.returnUrl]);
    },
    error => {
        console.log(error);
        this.alertService.error(error);
        this.loading = false;
    });

这是解决该问题的一种相当直率且不令人兴奋的方法。如前所述,mergeMap 可以很好地为您服务。

查看这个快速示例。我建议使用 Observable 数据来了解正在发生的事情。在这种情况下,Observable.of 基本上就像虚假的网络请求一样。

http://jsbin.com/pohisuliqo/edit?js,console

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多