0

I need to get name after user logged in via social network. But console.log(name) returns undefined. Why?

login() {
        var that = this;    
        var vk = {
            data: { user: { first_name: '', last_name: '', id: null } },
            init: new Promise(function (resolve, reject) {
                VK.init({ apiId: 6480684 });
                load();

                function load() {
                    VK.Auth.login(authInfo);

                    function authInfo(response) {
                        if (response.session) {
                            vk.data.user = response.session.user;
                            resolve();
                        } else {
                            reject();
                        }
                    }
                }
            })
        }

        async function data() {
            await vk.init;
            console.log('vk login');
            that.name = vk.data.user.first_name + ' ' + vk.data.user.last_name;
            that.id = vk.data.user.id;
            that.db.object('users/' + vk.data.user.id).set({
                id: vk.data.user.id,
                displayName: that.name
            });
        }
        data();
        console.log(this.name);
    }

After this function user added to database, but name is undefined.

  • What is the output of the vk.data.user.firstname/lastname? – zachbugay Jun 02 '18 at 11:57
  • 2
    `console.log(this.name);` execute before `that.name = ...` you sohuld to `await data(); ` – Michael Jun 02 '18 at 11:57
  • @Michael Thank you, now this console.log works. But if I want to use this variable from another component it returns undefined. I have this code: `VK.Observer.subscribe('auth.login', response => { this.isLoggedIn = true; this.router.navigate(['']); console.log(this.login.name); this.afService.displayName = this.login.name; }); ` (login refurs to LoginComponent) Can you help with it? – Иван Сидоров Jun 02 '18 at 12:05
  • Your question does not contain enough data to properly answer this question, try open another question – Michael Jun 02 '18 at 12:25
  • ok, thanks, i'll post another question – Иван Сидоров Jun 02 '18 at 12:30
  • @Michael My new question has been deleted as duplicate, so could you explain me please, why If I type `LoginComponent.name` instead of `that.name` I have error `Cannot assign to 'name' because it is a constant or a read-only property.` – Иван Сидоров Jun 02 '18 at 13:51

0 Answers0