簡體   English   中英

Angular 無法讀取未定義的屬性“id”

[英]Angular Cannot read property 'id' of undefined

我正在從休息中獲取用戶列表。 我需要在數據表(ng-prime)中列出這些用戶。 如果您單擊一行,它應該會讓您到達所需的路線([hostname]/users/edit/[userId]工作正常!

但是,如果我刷新頁面,則會出現上述錯誤。 我想了解為什么會這樣。

用戶管理.service.ts:

// imports are here//
@Injectable({
  providedIn: 'root'
})
export class UserManagementService {

  selectedUser: {};
  private usersList: UserListDTO[] = [];

  constructor(private userResoService: UserResourceService) { }

  getUsers() {
    this.userResoService.findPrivilegedUsersUsingGET().subscribe(resp => {
      resp.forEach(user => this.usersList.push(user));
    });
  }

  getUsersList(): UserListDTO[] {
    return this.usersList;
  }
}

用戶列表.component.ts:

export class UsersListComponent implements OnInit {

  cols: any[];
  listOfUsers = [];
  constructor(private userService: UserManagementService,
    private router: Router,
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.userService.getUsers();
    this.listOfUsers = this.userService.getUsersList();
    this.cols = [
      { field: 'firstName', header: 'First Name' },
      { field: 'lastName', header: 'Last Name' },
      { field: 'email', header: 'email' },
      { field: 'status', header: 'Status' }
    ];
  }

  private navigateToUserEdit() {
    const id = this.userService.selectedUser['id'];
    this.router.navigate(['edit', id], { relativeTo: this.route });
  }

  onRowSelect(event) {
    this.userService.selectedUser = event['data'];
    this.navigateToUserEdit();
  }

  deleteUser(user) {
    this.userService.selectedUser = user;
  }
}

編輯-user.component.ts:

export class EditUserComponent implements OnInit {

  constructor(private userService: UserManagementService) { }

  userToEdit: {};
  ngOnInit() {
    this.userToEdit = this.userService.selectedUser;
  }
}

編輯-user.component.html:

<p>
  {{userToEdit['id']}}
</p>

我在最后一個文件中收到錯誤。 我在想,由於某些生命周期掛鈎,它可能不存在,但是我該如何解決這個問題? 請啟發我的人。

編輯!:好的! 如果我在導航后檢查用戶 Obj 很好,但如果我刷新頁面userToEdit = undefined 我怎樣才能拿回那個Obj?

或者我該怎么做才能擁有它? 請不要告訴我使用本地存儲。

只需像這樣使用 ngIf 添加驗證:

編輯-user.component.html:

<p *ngIf="userService.selectedUser | async">
  {{userToEdit['id']}}
</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM