【问题标题】:Angular ERROR TypeError: Cannot read property 'userName' of undefinedAngular ERROR TypeError:无法读取未定义的属性“用户名”
【发布时间】:2021-01-16 08:06:55
【问题描述】:

我是 Angular 的新手,所以请耐心等待。

我想在我的 Angular 10 应用程序中获取当前用户的用户名但是当我尝试加载仪表板时,我收到以下错误。后端使用.net 5 web api开发。

    ERROR TypeError: Cannot read property 'userName' of undefined
    at ProfileComponent.loadMember (profile.component.ts:29)
    at ProfileComponent.ngOnInit (profile.component.ts:23)
    at callHook (core.js:3038)
    at callHooks (core.js:3008)
    at executeInitAndCheckHooks (core.js:2960)
    at refreshView (core.js:7186)
    at refreshEmbeddedViews (core.js:8279)
    at refreshView (core.js:7195)
    at refreshComponent (core.js:8325)
    at refreshChildComponents (core.js:6964)

这是我在 Profile 组件中尝试获取用户详细信息的代码

export class ProfileComponent implements OnInit {
    staff!: Staff;
    user!: User;

    constructor(private accountService: AuthenticationService, private staffService: StaffService) {

        this.accountService.currentUser$.pipe(take(1)).subscribe(user => this.user = user);

    }

    ngOnInit(): void {
        this.loadMember();

    }

    loadMember() {

        this.staffService.getStaff(this.user.userName).subscribe(staff => {
            this.staff = staff;
        })
    }

  
}    

我这里的 StaffService 代码是从 api 获取人员服务的代码

      getStaff(userName: string) {
        console.log(this.memberCache); 
    const member = [...this.memberCache.values()].reduce((arr, elem) => arr.concat(elem.result), [])
    .find((member: Staff) => member.userName === userName);

    if(member){
      return of(member);
    }
    console.log(member);
    return this.http.get<Staff>(this.baseUrl + 'AppUsers/staffByUserName/' + userName)
  }

我不明白为什么它不工作我试图 conole out this.user.userName 但它只返回未定义。有没有办法解决这个问题?

【问题讨论】:

  • 您在收到 this.accountService.currentUser$.. service 的值之前调用了 loadMember() 函数。
  • ngOnInit(): void { this.accountService.currentUser$.pipe(take(1)).subscribe(user => { this.user = user; this.loadMember(); }); }
  • 在构造函数上我试图获取它,或者你能告诉我解决方案
  • 错误很简单,用户名不存在。当您在构造函数中订阅时,将用户对象记录到控制台并查看用户名对象是否存在。错误肯定在那个区域附近。

标签: javascript angular angular10


【解决方案1】:

您应该这样做,以便您只管理一个订阅。

export class ProfileComponent implements OnInit {
    staff: Staff;
    user: User;

    constructor(private accountService: AuthenticationService, private staffService: StaffService) {

 

    }


  ngOnInit(): void {
        this.loadMember();

    }

    loadMember() {
    
      this.accountService.currentUser$
      .pipe(take(1), switchMap(user => this.staffService.getStaff(user.userName)))
      .subscribe(staff => {
        this.staff = staff;
      }) 
    }

}

【讨论】:

    【解决方案2】:

    看起来组件在 accountService 收到响应之前就已初始化,因此当您调用 getStaff(this.user.username) 时,用户仍未被初始化。

    尝试延迟对this.loadMember() 的调用,直到用户被初始化:

       ngOnInit(): void {
         this.accountService.currentUser$.pipe(take(1)).subscribe(user =>{
           this.user = user;
           this.loadMember(this.user.username);
         });
       }
    

    【讨论】:

    • 它可以工作,但是当我尝试刷新页面时,当我尝试获取用户时没有显示任何内容
    • 你能调试代码,缩小问题所在吗?后端是否返回预期的响应?是否为 staff 实例变量分配了正确的值?
    【解决方案3】:

    为避免值未初始化的问题,您可以在 Observables 中使用 rxjs 运算符;

      export class ProfileComponent implements OnInit {
        staff: Staff;
        user: User;
        // Define staff and user Observables. Use tap operator from 'rxjs/operators' to assign the values. Use mergeMap operator to call the getStaff function
        user$: Observable<User> = this.accountService.currentUser$.pipe(
          take(1),
          tap(user => this.user = user)
        );
        staff$: Observable<Sfaff> = this.staff$.pipe(
           mergeMap(({userName}) => this.staffService.getStaff(userName)),
           tap(staff => this.staff = staff)
        );
    
        constructor(private accountService: AuthenticationService, private staffService: StaffService) {
            
        }
    
        ngOnInit(): void {
            user$.subscribe();
            staff$.subscribe();
    
        }
    
      
    }  
    
    

    【讨论】:

      猜你喜欢
      • 2022-07-26
      • 1970-01-01
      • 2018-12-18
      • 2022-11-07
      • 2018-11-30
      • 2019-02-06
      • 1970-01-01
      • 2019-07-27
      • 2016-05-08
      相关资源
      最近更新 更多