R
R
Roman Tishakov2016-04-17 23:12:37
JavaScript
Roman Tishakov, 2016-04-17 23:12:37

How to properly trigger observer update in Angular 2?

There is a code that receives all data (from VK), but does not draw a list of users ...
FILE AuthView.ts

import {Component, Inject} from 'angular2/core';
import {UsersService} from '../services/UsersService';

@Component({
    selector: 'users-list',
    template: `
        <h1>Список пользователей</h1>
        <ul class="nav nav-pills nav-stacked">
            <li role="presentation" *ngFor="#user of currentUsers">
                <a href="#">
                    {{ user.first_name }}
                </a>
            </li>
        </ul>
    `
})
export class UsersList {
    private currentUsers = [];

    constructor(@Inject(UsersService) private UsersService) {
        UsersService.users.subscribe(newUsers => {
            this.currentUsers = newUsers;
        });
        UsersService.fetchUsers();
    }

}

FILE UsersService.ts:
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class UsersService {

    public users: Observable<any>;
    private _usersObserver: any;
    private _users:any = [];


    constructor() {
        this.users = new Observable(observer => {
            this._usersObserver = observer;
        });

        this.Init();
    }
    fetchUsers() {
        this._usersObserver.next(this._users);
    }

    private getUsers () {
        VK.Api.call('friends.get', {fields: ['photo_50']}, (r) =>{
            if(r.response) {
                this._users = r.response;
                console.log("Пользователи загружены!");
                this.fetchUsers();
            }else{
                console.log("Ошибка получения пользователей!");
            }
        });
    }

    Init() {
        window.onload = () => {
            VK.init({
                apiId: 5419902
            });
            this.CheckStatusLogin();
        };

    }

    CheckStatusLogin() {
        VK.Auth.getLoginStatus((response)=> {
            if (response.session && localStorage.getItem('user.session')!== null) {
                console.log("/* Пользователь авторизован, продолжаем работу */");
                this.getUsers();
            } else {
                VK.Auth.login((response) => {
                    if (response.session) {
                        localStorage.setItem('user.session', JSON.stringify(response.session) );
                        console.log('/* Пользователь успешно авторизовался */');

                    } else {
                        console.log('/* Пользователь нажал кнопку Отмена в окне авторизации */');
                        return false;
                    }
                });
            }
        })
    }
}

I've been sitting with this for an hour now.
WHAT AM I DOING WRONG? :-'((((((((((

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-04-18
@BigRoma

Not really sure about the solution, but it should work. The asynchronous call code with the contact api works separately from the angular zone. Namely, zone notifies Angular about changes. Angular 2 Change Detection Explained . Those. you will have to force change detection.

import {Component, Inject, NgZone} from 'angular2/core'; // import NgZone
...
constructor(@Inject(UsersService) private UsersService, private zone:NgZone) {
  UsersService.users.subscribe(newUsers => {
    this.zone.run(()=> {
      this.currentUsers = newUsers;
    });
  });
  UsersService.fetchUsers();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question