首页 > 解决方案 > ngAfterViewInit 不使用全局变量

问题描述

它很简单,同时也很复杂。在我的组件的初始化中,我订阅以获取 userInfo 并获取他的昵称。在那之前没关系。一切工作正常。但是我添加了一个 ngAfterViewInit() 以便能够使用分页器。如果我直接使用我的用户名作为字符串,它是有效的。但如果我使用我的变量则不起作用。

** 在 ngAfterViewInit 中,如果我使用 'myname' 它可以工作。如果我使用 this.login_info.nickname ,我的浏览器会显示:Cannot read property 'nickname' of undefined

这是代码:

import {
  Component,
  OnInit,
  ChangeDetectorRef,
  ViewChild,
  ɵConsole
} from '@angular/core';
import { Sprint } from '../models/sprint';
import { DataService } from '../services/data.service';
import {
  MatTableDataSource,
  MatDialog,
  MatPaginator,
  MatPaginatorModule
} from '@angular/material';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { utils } from '../utils/utils';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DataPaginatedService } from '../services/data-paginated.service';
import { startWith, tap } from 'rxjs/operators';

@Component({
  selector: 'app-past-sprints',
  templateUrl: './past-sprints.component.html',
  styleUrls: ['./past-sprints.component.css']
})
export class PastSprintsComponent implements OnInit {
  pastSprint: Sprint;
  // dataSource$: Observable<Sprint[]>;
  dataSource$ = new MatTableDataSource([]);
  dataSource2: DataPaginatedService;
  private login_info: any;
  totalCount: number;

  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;

  displayedColumns = ['user', 'name', 'status', 'description', 'duration'];
  httphome: HttpClient = {} as HttpClient;

  constructor(
    private route: ActivatedRoute,
    public dialog: MatDialog,
    private pastSprintService: DataService,
    private auth: AuthService,
    private dataPaginatedService: DataPaginatedService
  ) {}

  ngOnInit() {
    // this.pastSprint = this.route.snapshot.data['pastSprint'];
    this.dataSource2 = new DataPaginatedService(this.pastSprintService);
    this.auth.getUser$().subscribe(val => {
      this.login_info = val;
      console.log('hummm-val-log', val.nickname);
      this.loadData();
      this.dataSource2.loadUserSprint(
        this.login_info.nickname,
        '',
        'asc',
        0,
        2
      );
      this.dataSource2.totalCountItem.subscribe(total => {
        this.totalCount = total;
      });
    });
  }

  addData(newSprint: Sprint) {
    // this.dataSource$.data.push;
    // const data = this.dataSource$.data;
    // data.push(newSprint);
    // this.dataSource$.data = data;
  }

  loadData() {
    const user = this.auth.getUser$();

    this.pastSprintService
      .findAllPastSprint(this.login_info.nickname)
      //.findAllPastSprint(document.getElementById('nickname').innerHTML) //
      .subscribe((past: any) => {
        this.dataSource$.data = past;
        console.log('past', past);
      });

    this.dataSource2 = new DataPaginatedService(this.pastSprintService);
  }
  openDialog() {
    const dialogRef = this.dialog.open(DialogContentExampleDialog);

    dialogRef.afterClosed().subscribe(async result => {
      if (result) {
        console.log(`Just: ${result}`);
        const myService = new DataService(this.httphome);
        await myService.deleteAll(this.login_info.nickname);
      }
      console.log(`Dialog result: ${result}`);
    });
  }

  ngAfterViewInit() {
    this.paginator.page
      .pipe(
        startWith(null),
        tap(() => {
          this.dataSource2.loadUserSprint(
            this.login_info.nickname, //This line doesn't work
                            'myname' //this line work.
            '',
            'asc',
            this.paginator.pageIndex,
            this.paginator.pageSize
          );
          console.log('TAP', 'myname');
          this.dataSource2.totalCountItem.subscribe(total => {
            this.totalCount = total;
          });
        })
      )
      .subscribe();
  }
}
@Component({
  selector: 'dialog-content-example-dialog',
  templateUrl: 'DeleteAll_Dialog.html'
})
export class DialogContentExampleDialog {}

我不能给你数据源的数据库连接。

前面的代码是:

<div>
  <mat-table
    #tablepaginated
    class="pastSprint-table mat-elevation-z8"
    [dataSource]="dataSource2"
    matSort
    matSortActive="user"
    matSortDirection="asc"
    matSortDisableClear
  >
    <ng-container matColumnDef="user">
      <mat-header-cell *matHeaderCellDef mat-sort-header>User</mat-header-cell>

      <mat-cell *matCellDef="let pastSprint">{{ pastSprint.user }}</mat-cell>
    </ng-container>

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef>Description</mat-header-cell>

      <mat-cell class="description-cell" *matCellDef="let pastSprint">{{
        pastSprint.description
      }}</mat-cell>
    </ng-container>

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef>Length</mat-header-cell>
      <mat-cell class="duration-cell" *matCellDef="let pastSprint">{{
        pastSprint.sprintType.name
      }}</mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef>Status</mat-header-cell>
      <mat-cell class="duration-cell" *matCellDef="let pastSprint">{{
        pastSprint.sprintType.status
      }}</mat-cell>
    </ng-container>

    <ng-container matColumnDef="duration">
      <mat-header-cell *matHeaderCellDef>Duration</mat-header-cell>
enter code here
      <mat-cell class="duration-cell" *matCellDef="let pastSprint">{{
        pastSprint.sprintType.duration
      }}</mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
  </mat-table>
  <mat-paginator
    [length]="totalCount"
    [pageSize]="2"
    [pageSizeOptions]="[2, 4, 10]"
  ></mat-paginator>
</div>

但我的问题是:为什么在我的类中定义并在 ONINIT 中接收数据的变量在 AfterViewInit 中不可用?谢谢

标签: angular

解决方案


这是一个简单的答案,它被称为是scope两个不同的函数,在它们内部声明的任何变量都将是这些函数的本地变量。一个简单的解决方法是:ngOnInit()afterViewInit()


var variableName = yourVariableValue;

ngOnInit() {
   variableName = whatever it should be equal to here
}

afterViewInit() {
  // Now whatever you defined the variable as in ngOnInit() can be used here!
}

推荐阅读