我有一个名为 edit-scrim 的组件,在我的组件内部,我有 2 个模型“团队”类型的数组,我正在使用导入到组件中的服务中的一些方法来为数组分配值。在我第一次访问该页面时,数组被填充得很好,但是如果我使用 router.navigate() 转到另一个页面并使用 routerlink 返回到“edit-scrim”,它会丢失其中一个数组的数据。我将数据分配给数组的所有功能都在 ngOnInit 内部,我在这个方法中做了一个 console.log("check") 来查看它是否在我每次访问组件时都被调用并且它被调用所以我没有确定出了什么问题。
如果我刷新我的页面,数据会返回,但如果我再次通过路由器链接访问它,它不会
这些是我在 component.ts 文件中的数组
teams: Team[];
myTeams: Team[] = [];
附件是我的 ngOnInIt 方法的代码片段,我使用 routerlink 访问另一个页面并返回到“edit-scrim”并且数据消失了。
ngOnInit() {
console.log("check");
this.myinit();
}
myinit() {
this.authService.getAuth().subscribe(auth => {
if (auth) {
this.loggedInUser = auth.email;
} else {
}
});
this.teamService.getTeams().subscribe(teams => {
this.teams = teams;
console.log(this.teams);
for (var i = 0; i < this.teams.length; i++) {
if (this.teams[i].createdBy == this.loggedInUser) {
this.myTeams.push(this.teams[i]);
}
}
});
console.log(this.myTeams);
this.id = this.route.snapshot.params['id'];
//Get Team
this.scrimService.getScrim(this.id).subscribe(scrim => {
this.scrim = scrim;
});
}
编辑 当我在我的 init 函数中执行此操作时,我第一次访问我的页面时,控制台会记录正确的数据,如果我转到另一个页面并返回此页面,它就会丢失。:/
this.teamService.getTeams().subscribe(teams => {
this.teams = teams;
console.log(this.teams);
// this.myTeams = this.teams.filter(function (team) { return
team.createdBy == this.loggedInUser; });
this.myTeams = this.teams.filter(team => team.createdBy ==
this.loggedInUser)
console.log(this.myTeams);
});
编辑2
this.authService.getAuth().subscribe(auth => {
if (auth) {
this.loggedInUser = auth.email;
this.teamService.getTeams().subscribe(teams => {
this.teams = teams;
console.log(this.teams);
//this.myTeams = this.teams.filter(function (team) { return team.createdBy == this.loggedInUser; });
this.myTeams = this.teams.filter(team => team.createdBy == this.loggedInUser)
console.log(this.myTeams);
});
} else {
}
});
EDIT3 - >没有这样工作:/也许我搞砸了语法?
this.authService.getAuth().subscribe(auth => {
if (auth) {
this.loggedInUser = auth.email;
}
},
error => { console.log(error) },
() => {
this.teamService.getTeams().subscribe(teams => {
this.teams = teams;
this.myTeams = this.teams.filter(team => team.createdBy == this.loggedInUser);
console.log(this.teams);
console.log(this.myTeams);
});
});
编辑 4 - 没有用,它甚至没有进入执行 console.log 的阶段
this.authService.getAuth().subscribe(auth => {
if (auth) {
this.loggedInUser = auth.email;
}
},
error => { console.log(error) },
() => {
this.teamService.getTeams().subscribe(teams => {
this.teams = teams;
this.myTeams = this.teams.filter(team => team.createdBy == this.loggedInUser);
console.log(this.teams);
console.log(this.myTeams);
});
});