【问题标题】:Update variable by observer Angular/Typescript通过观察者 Angular/Typescript 更新变量
【发布时间】:2020-05-25 17:17:59
【问题描述】:

这是我的代码:

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 始终为空,看来观察者不起作用。 你能帮帮我吗?

【问题讨论】:

    标签: angular typescript observable subject


    【解决方案1】:

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

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

    【讨论】:

    • ERROR 错误:未捕获(承诺中):TypeError:无法设置未定义的属性“AllUsers” TypeError:无法设置未定义的属性“AllUsers”。有关完整错误,请参阅我的评论
    • 不客气 :) 它说未定义,因为“this”与 foreach 中的函数(childSnapshot)相关,所以我们将服务“this”更改为那个
    【解决方案2】:

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

    服务

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

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

    这里有更多详细信息:https://stackoverflow.com/a/34361380/6513921

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

    有关如何访问异步数据的更多详细信息,请参见此处:https://stackoverflow.com/a/14220323/6513921

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-07
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      相关资源
      最近更新 更多