0

I need to change name and id after login() function. But this

that.name = vk.data.user.first_name + ' ' + vk.data.user.last_name;
that.id = vk.data.user.id;

creates local variables name and id. How can I change name and id of LoginComponent class?

Login component:

import { Component, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFire } from '../shared';
import {
    AngularFireDatabase,
    AngularFireDatabaseModule,
    FirebaseListObservable,
    FirebaseObjectObservable
} from 'angularfire2/database';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})

@Injectable()
export class LoginComponent {
    public error: any;
    public name: string;
    public id: number;

    constructor(public afService: AngularFire, private router: Router, public db: AngularFireDatabase) { }

    async login() {
        var that = this;    
        var vk = {
            data: { user: { first_name: '', last_name: '', id: null } },
            appID: 6480684,
            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: that.id,
                displayName: that.name
            });
        }
        await data();
    }

Chat component:

import { Component, AfterViewChecked, ElementRef, ViewChild, Input, OnChanges } from '@angular/core';
import { FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';
import { LoginComponent } from '../../login/login.component';

import { AngularFire } from '../../shared';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css']
})
export class ChatComponent implements AfterViewChecked, OnChanges {
  @ViewChild('scroller') private myScrollContainer: ElementRef;
  @Input() channelId;

  public messages: FirebaseListObservable<any>;
  imageSrc: string;
  public newMessage: string;
  public newImage: any;

  constructor(public afService: AngularFire, public afAuth: AngularFireAuth, public login: LoginComponent) {}

  ngOnChanges() {
    this.messages = this.afService.getMessages(this.channelId);
  }

        async sendMessage() {
            var name;
            if (this.afAuth.auth.currentUser !== null) {
                name = await this.afService.getDisplayName();
            } else {
                name = this.login.name;
                console.log(name);
            }
        this.afService.sendMessage(this.channelId, this.newMessage, name);
    this.newMessage = '';
  }
  • 1
    Use fat arrow operator `(=>)` instead of `function`, so that you don't need to use `that` instead of `this`. – Amit Chigadani Jun 02 '18 at 13:39
  • How is `login()` being called? – ConnorsFan Jun 02 '18 at 13:41
  • @ConnorsFan from login.component.html after button click `
    `
    – Иван Сидоров Jun 02 '18 at 13:43
  • Possible duplicate of [How to get name after login() function](https://stackoverflow.com/questions/50656652/how-to-get-name-after-login-function) – R. Richards Jun 02 '18 at 13:45
  • Should it be worth noting that your code has variables vk and VK which are not the same? Have you run the code and checked the console for errors? – JeffryHouser Jun 02 '18 at 13:57
  • @AmitChigadani I've changed code to `var data = async () => { await vk.init; console.log('vk login'); this.name = vk.data.user.first_name + ' ' + vk.data.user.last_name; this.id = vk.data.user.id; this.db.object('users/' + vk.data.user.id).set({ id: this.id, displayName: this.name }); } await data();` but same result – Иван Сидоров Jun 02 '18 at 13:58
  • @JeffryHouser It works with no errors. But I can't use name and id from another component. Also, 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 14:03
  • @ИванСидоров Can you show how you are trying to access the values in different components? – Amit Chigadani Jun 02 '18 at 14:17
  • @AmitChigadani I have chat component with `import { LoginComponent } from '../../login/login.component';` .... `constructor(...public login: LoginComponent) {}` and function `async sendMessage() { var name; if (this.afAuth.auth.currentUser !== null) { name = await this.afService.getDisplayName(); } else { name = this.login.name; console.log(name); }` Before login component @Injectable() – Иван Сидоров Jun 02 '18 at 14:36
  • Please add all your code inside the question – Amit Chigadani Jun 02 '18 at 14:37
  • @AmitChigadani I've changed question – Иван Сидоров Jun 02 '18 at 14:41
  • You cannot inject a component inside another component. Instead you can share your component data to other component via some angular service. You will find number of posts to share data between components. Have a look at them. What you are doing is not correct. – Amit Chigadani Jun 02 '18 at 14:50
  • @AmitChigadani Ok, I will try to do it via service, thank you Amit! – Иван Сидоров Jun 02 '18 at 14:56

0 Answers0