angular - 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 中不可用?谢谢
解决方案
这是一个简单的答案,它被称为是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!
}
推荐阅读
- ruby-on-rails - 如何使用 Devise 和 STI 在 Rails 中向用户类型添加自定义字段?
- graph - SPARQL 查询以根据属性值比较从不同的图创建合并图
- python-3.x - 从控制台(测试)和通过 AWS Gateway REST API 调用时,Lambda 的行为有所不同
- ruby - rubymine 中是否有可用于breakman 的插件?
- java - 如何在springBoot应用程序(application.properties)中配置“idle_in_transaction_session_timeout”数据库属性
- c++ - QT c++:插入多行编辑
- php - 如何在 Mailjet 分页中获取最后一页或总记录
- excel - 我想存档按钮所做的操作,但我的组合框中出现错误,不知道为什么
- javascript - 活动选择结束
- android - 应用程序特定目录未在 android 的外部存储目录中创建