订阅上的Angular2设置变量不起作用 [英] Angular2 set variable on subscribe not working

查看:63
本文介绍了订阅上的Angular2设置变量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对angular2还是很陌生,但是我尝试编写一个登录组件.一切正常,除非成功登录后,我想在会话服务中设置用户名和密码(我在其中存储用户名和密码以创建基本身份验证标头).遗憾的是 this._session.loggedIn 从未设置.有人知道为什么吗?

I am quite new to angular2 but i tried to write a login component. Everything works fine except after a successful login i want to set the username and password in my session service (where i store the username and password to create basic auth headers). Sadly this._session.loggedIn never gets set. Anybody an idea why?

export class LoginComponent {

    public email = '';
    public password = '';

    constructor(
        private _router: Router,
        private _auth: AuthenticationService,
        private _session: SessionService) {
    }

    login() {
        this._auth.login(this.email, this.password)
            .subscribe(
                data => {
                    this._session.currentProfile = data;
                    this._session.loggedIn = true;
                    this._router.navigate(['Home']);
                },
                err => {}
            );
    }
}

AuthenticationService:

AuthenticationService:

login(email, password){
        return this._http.get('/profile')
            .map(res => res.json());
}

推荐答案

此代码是传递给 subscribe

        data => {
            this._session.currentProfile = data;
            this._session.loggedIn = true;
            this._router.navigate(['Home']);
        }

此代码不会立即执行,但有时会在服务器响应到达时或观察到的对象发出新事件所需的任何事件之后立即执行,从而导致上述函数被调用.

This code is not executed immediately but sometimes later, when the response from the server arrives or whatever event is necessary for the observable to emit a new event which then causes above function to be called.

这是

login() {
    this._auth.login(this.email, this.password)
        .subscribe(
            data => {
                this._session.currentProfile = data;
                this._session.loggedIn = true;
                this._router.navigate(['Home']);
            },
            err => {}
        );
    // <<== at this point above code hasn't been executed yet and no values are set
}

如果您需要在数据到达时执行代码,则需要将其移动到回调中.

If you need code to be executed when the data arrives, you need to move it inside the callback.

如果 login 的调用者需要访问接收到的数据,则它还必须等待直到数据到达.您可以通过返回可观察值

If the caller of login needs access to the received data, it has to wait as well until the data arrives. You can achieve this by returning the observable

login() {
    return this._auth.login(this.email, this.password)
        .map(
            data => {
                this._session.currentProfile = data;
                this._session.loggedIn = true;
                this._router.navigate(['Home']);
            }
        );
}

在这种情况下,您不能使用 subscribe ,因为它会返回 Subscription .如果改为使用 map ,则将返回 Observable ,可由调用方使用,如

You can't use subscribe in this case because it returns a Subscription. If you use map instead, then a Observable is returned which can be used by the caller like

this.login().subscribe(data => this.doSomething());

这样,当调用 doSomething()时,设置 _session.currentProfile _session.loggedIn router.navigate()已被调用.

This way when doSomething() is called, _session.currentProfile, _session.loggedIn are set and router.navigate() has been called.

总是需要正确地链接异步执行,并且没有办法返回异步调用来同步执行.

Async execution always needs to be properly chained and there is no way to go back to sync execution from an async call.

这篇关于订阅上的Angular2设置变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆