Обновить переменную наблюдателем Angular / Typescript - PullRequest
0 голосов
/ 25 мая 2020

Вот мой код:

UtilisateursService.ts

public AllUsers:Utilisateur[]=[{ UserId:'',firstName:'', lastName:'',email:'',phoneNumber:null,roles:'',active:"false",createdBy:'',createdDate:null,lastModifiedBy:'',lastModifiedDate:null,},];

  **public userSubject = new Subject<Utilisateur[]>();**
  //userSubject2 = new Subject<Classe[]>();

  emitUsers(u:Utilisateur[]) {
    this.userSubject.next(u.slice());
        }


getAllUsers() {

           var childsdata:Utilisateur[]=[];
           firebase.database().ref("/users").orderByKey().once("value").then(function(snapshot) {
               snapshot.forEach(function(childSnapshot) {
                 childsdata.push(childSnapshot.val());
             });
           });

           this.AllUsers=childsdata;
            this.emitUsers(this.AllUsers);

           console.log("this.AllUsers = ",this.AllUsers);

  };

ListeUtilisateursComponent.ts

export class ListeUtilisateursComponent implements OnInit,OnDestroy {
  // users: Utilisateur[];
  usersSubscription: Subscription;
  displayedColumns: string[] = ['nom', 'prenom', 'email', 'role','active','actions'];
  **UserdataSource;**

  constructor(private usersService: UtilisateursService,private router: Router) { }

  ngOnInit() {
    this.usersService.userSubject.subscribe((AllUsers) => {
      **this.UserdataSource = AllUsers;**
    });


    this.usersService.getAllUsers();


    // this.UserdataSource=this.usersService.getAllUsers();
    console.log("Dans ngOnInit, this.UserdataSource ==== ",this.UserdataSource);

  }

ListeUtilisateursComponent. html

<table mat-table [dataSource]="*UserdataSource*" class="mat-elevation-z8">
  <ng-container matColumnDef="nom">
    <th mat-header-cell *matHeaderCellDef> Nom </th>
    <td mat-cell *matCellDef="let element"> {{element.lastName}} </td>
  </ng-container>

  <ng-container matColumnDef="prenom">
    <th mat-header-cell *matHeaderCellDef> Prénom </th>
    <td mat-cell *matCellDef="let element"> {{element.firstName}} </td>
  </ng-container>

  <ng-container matColumnDef="email">
    <th mat-header-cell *matHeaderCellDef> Email </th>
    <td mat-cell *matCellDef="let element"> {{element.email}} </td>
  </ng-container>

переменная AllUsers в UtilisateurService обновляется правильно. Переменная UserdataSource всегда пуста, кажется, что наблюдатель не работает. Не могли бы вы мне помочь?

Ответы [ 2 ]

1 голос
/ 25 мая 2020

поместите их в свой запрос. это асинхронный c вызов, ваши данные могут все еще не заполняться, пока вы пытаетесь выполнить вне запроса

 getAllUsers() {
  var that=this;
  var childsdata:Utilisateur[]=[];
  firebase.database().ref("/users").orderByKey().once("value").then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
           childsdata.push(childSnapshot.val());
           that.AllUsers=childsdata;
           that.emitUsers(that.AllUsers);
            console.log("that.AllUsers = ",that.AllUsers);
         });
      });
 };
0 голосов
/ 25 мая 2020

Есть проблемы в обслуживании и компоненте. В обоих случаях доступ к асинхронным данным осуществляется синхронно.

Сервис

childsdata назначается асинхронно, поэтому оператор this.AllUsers = childsdata; и другие состояния, зависящие от this.AllUsers, должны находиться в пределах then enclosure.

А для доступа к переменным-членам внутри обратных вызовов функции, определенные с помощью ключевого слова function, должны быть заменены стрелочными функциями. Значение ключевого слова this в традиционной функции JS обозначает область действия функции, а в функции стрелки обозначает класс.

Подробнее об этом здесь: { ссылка }

public AllUsers: Utilisateur[] = [{ UserId: '', firstName: '', lastName: '', email: '', phoneNumber: null, roles: '', active: "false", createdBy: '', createdDate: null, lastModifiedBy: '', lastModifiedDate: null},];

public userSubject = new Subject<Utilisateur[]>();

emitUsers(u: Utilisateur[]) {
  this.userSubject.next(u.slice());
}

getAllUsers() {
  let childsdata: Utilisateur[] = [];
  firebase.database().ref("/users").orderByKey().once("value").then((snapshot) => {    // <-- arrow function here
      snapshot.forEach((childSnapshot) => {    // <-- arrow function here
        childsdata.push(childSnapshot.val());
        this.AllUsers = childsdata;
        this.emitUsers(this.AllUsers);
        console.log("this.AllUsers = ",this.AllUsers);
    });
  });
};

Компонент

UserdataSource назначается асинхронно, поэтому журнал консоли, который его распечатывает, должен находиться в рамках подписки.

export class ListeUtilisateursComponent implements OnInit,OnDestroy {
  // users: Utilisateur[];
  usersSubscription: Subscription;
  displayedColumns: string[] = ['nom', 'prenom', 'email', 'role','active','actions'];
  **UserdataSource;**

  constructor(private usersService: UtilisateursService,private router: Router) { }

  ngOnInit() {
    this.usersService.userSubject.subscribe((AllUsers) => {
      this.UserdataSource = AllUsers;
      console.log("Dans ngOnInit, this.UserdataSource ==== ", this.UserdataSource);
    });
    this.usersService.getAllUsers();
  }
}

Подробнее см. Здесь о том, как получить доступ к асинхронным данным: { ссылка }

...