Angular ngAfterViewInit不';不要使用全局变量
它简单,同时又复杂。在我的组件初始化过程中,我订阅以获取userInfo和他的昵称。在那之前没关系。一切正常。 但是我添加了一个ngAfterViewInit()来使用paginator。如果我直接使用用户名作为字符串,它是有效的。但如果我使用变量,则不起作用 **在ngAfterViewInit中,如果我使用“myname”,它会工作。如果我使用这个.login\u info.昵称,我的浏览器会显示:无法读取未定义的属性“昵称” 代码如下:Angular ngAfterViewInit不';不要使用全局变量,angular,Angular,它简单,同时又复杂。在我的组件初始化过程中,我订阅以获取userInfo和他的昵称。在那之前没关系。一切正常。 但是我添加了一个ngAfterViewInit()来使用paginator。如果我直接使用用户名作为字符串,它是有效的。但如果我使用变量,则不起作用 **在ngAfterViewInit中,如果我使用“myname”,它会工作。如果我使用这个.login\u info.昵称,我的浏览器会显示:无法读取未定义的属性“昵称” 代码如下: import { Component, On
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 {}
导入{
组成部分,
奥尼特,
改变,
ViewChild,
ɵ控制台
}从“@angular/core”开始;
从“../models/Sprint”导入{Sprint};
从“../services/data.service”导入{DataService};
进口{
MatTableDataSource,
MatDialog,
MatPaginator,
matpaginatromodule
}从“@角度/材料”开始;
从'@angular/router'导入{ActivatedRoute};
从“../services/auth.service”导入{AuthService};
从“../utils/utils”导入{utils};
从“rxjs”导入{Observable};
从'@angular/common/http'导入{HttpClient};
从“../services/data paginated.service”导入{DataPaginatedService};
从“rxjs/operators”导入{startWith,tap};
@组成部分({
选择器:“应用程序通过冲刺”,
templateUrl:“./pass sprint.component.html”,
样式URL:['./过去的sprint.component.css']
})
导出类PastSprintComponent实现OnInit{
短跑:短跑;
//数据源$:可观察;
dataSource$=新MatTableDataSource([]);
数据源2:数据分页服务;
私人登录信息:任何;
totalCount:数字;
@ViewChild(MatPaginator,{static:false})paginator:MatPaginator;
displayedColumns=[“用户”、“名称”、“状态”、“说明”、“持续时间”];
httphome:HttpClient={}作为HttpClient;
建造师(
专用路由:激活的路由,
公共对话:MatDialog,
专用服务:数据服务,
私有身份验证:身份验证服务,
专用dataPaginatedService:dataPaginatedService
) {}
恩戈尼尼特(){
//this.pastSprint=this.route.snapshot.data['pastSprint'];
this.dataSource2=新的DataPaginatedService(this.PasstSprintService);
this.auth.getUser$().subscribe(val=>{
this.login_info=val;
console.log('hummm-val-log',val.昵称);
这是loadData();
this.dataSource2.loadUserSprint(
this.login_info.昵称,
'',
“asc”,
0,
2.
);
this.dataSource2.totalCountItem.subscribe(总计=>{
this.totalCount=总计;
});
});
}
addData(新闻纸:Sprint){
//this.dataSource$.data.push;
//const data=this.dataSource$.data;
//数据推送(新闻纸);
//this.dataSource$.data=数据;
}
loadData(){
const user=this.auth.getUser$();
这是我们的服务
.findAllPastSprint(这个.login\u info.昵称)
//.findAllPastSprint(document.getElementById('昵称').innerHTML)//
.订阅((过去:任何)=>{
this.dataSource$.data=过去;
console.log(‘过去’,过去);
});
this.dataSource2=新的DataPaginatedService(this.PasstSprintService);
}
openDialog(){
const dialogRef=this.dialog.open(DialogContentExampleDialog);
dialogRef.afterClosed().subscribe(异步结果=>{
如果(结果){
log(`Just:${result}`);
const myService=新的数据服务(this.httphome);
等待myService.deleteAll(this.login\u info.昵称);
}
log(`Dialog result:${result}`);
});
}
ngAfterViewInit(){
这个是.paginator.page
.烟斗(
startWith(空),
点击(()=>{
this.dataSource2.loadUserSprint(
this.login\u info.昵称,//此行不起作用
“myname”//这行代码有效。
'',
“asc”,
this.paginator.pageIndex,
this.paginator.pageSize
);
log('TAP','myname');
this.dataSource2.totalCountItem.subscribe(总计=>{
this.totalCount=总计;
});
})
)
.subscribe();
}
}
@组成部分({
选择器:“对话框内容示例对话框”,
templateUrl:'DeleteAll_Dialog.html'
})
导出类对话框ContentExampleDialog{}
我无法为您提供数据源的数据库连接
前端代码为:
<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>
使用者
{{pastSprint.user}
描述
{{
pastSprint.description
}}
长度
{{
pastSprint.sprintType.name
}}
地位
{{
pastSprint.sprintType.status
}}
期间
在这里输入代码
{{
pastSprint.sprintType.duration
}}
但我的问题是:为什么在类中定义并在ONINIT中接收数据的变量在AfterViewInit中不可用?
谢谢这是一个简单的答案,因为
ngOnInit()
和afterViewInit()
是两个不同的函数,其中声明的任何变量都是这些函数的局部变量。一个简单的解决方案是:
var variableName=您的VariableValue;
恩戈尼尼特(){
variableName=此处应等于的值
}
afterViewInit(){
//现在,无论您在ngOnInit()中定义了什么变量,都可以在这里使用!
}
这是因为您异步检索昵称。Angular的Lifecycle Management调用ngAfterViewInit函数时,数据还不存在。@A.Winnen,好的,在启动ngAfterViewInit之前,有没有办法等待我的AvVariable被填充?或者订阅的方法?解决这个问题的最简单方法是将代码从ngOnInit移动到ngAfterViewInit,并链接观察对象。谢谢Jose,但是我的变量this\u login在类的开头声明:private login\u info:any;我在NGOnInit中设置了一个订阅信息,但这似乎是个问题