观察者更新变量 Angular/Typescript

Update variable by observer Angular/Typescript

这是我的代码:

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>

UtilisateurService 的变量 AllUsers 正确更新 变量 UserdataSource 一直是空的,看来观察者不起作用。 你能帮帮我吗?

将它们放入您的请求中。这是异步调用,当您在请求之外尝试时,您的数据可能仍未填充

 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);
         });
      });
 };

服务和组件存在问题。在这两种情况下,异步数据都是同步访问的。

服务

childsdata 是异步分配的,因此 this.AllUsers = childsdata; 语句和其他依赖于 this.AllUsers 的语句应该在 then 附件中。

并且要在回调中访问成员变量,用 function 关键字定义的函数应替换为箭头函数。 this关键字在传统JS函数中表示函数作用域,在箭头函数中表示class.

这里有更多详细信息:

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();
  }
}

有关如何访问异步数据的更多详细信息,请参阅此处: