Answer the question
In order to leave comments, you need to log in
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();
}
}
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;
}
});
}
})
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question