Angular5:ngOnInit 只在路由时调用一次



我有一个基本的应用程序,我可以使用数据服务从火库获取数据。我有几个页面(组件(,团队,球员,统计数据...

例如我的团队组件:

import { Component, OnInit } from '@angular/core';
import { TeamsService } from '../../services/teams.service';
import { Team } from '../../models/team';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'app-teams',
templateUrl: './teams.component.html',
styleUrls: ['./teams.component.css']
})
export class TeamsComponent implements OnInit {
public teams: Team[];
editState: boolean = false;
teamToEdit: Team;
showAdd: boolean = false;
showSelect: boolean = false;
selectedTeam: Observable<Team>;
constructor(public teamsService: TeamsService) {
}
ngOnInit() {
this.teamsService.getTeams().subscribe(teams => {
this.teams = teams;
console.log('ngOnInit invoked');
});
}
deleteTeam(event, team) {
const response = confirm('are you sure you want to delete?');
if (response) {
this.teamsService.deleteTeam(team);
}
return;
}
editTeam(event, team) {
this.editState = !this.editState;
this.teamToEdit = team;
}
updateTeam(team) {
this.teamsService.updateTeam(team);
this.teamToEdit = null;
this.editState = false;
}
showAddForm() {
this.showAdd = !this.showAdd;
}
getTeam(event, team) {
this.showSelect = !this.showSelect;
this.selectedTeam = this.teamsService.getTeamById(team.id);
}
}

在ngOnInit中,我将数据加载到局部变量中,但是一旦我导航到另一个页面然后返回,数据就消失了。我确实需要刷新页面以重新加载数据。

我应该如何解决这个问题?

创建解析程序防护,并在 TeamsComponent 的路由配置中使用它。此外,创建一个将执行数据检索的服务,并将其注入解析程序。此服务可以在用户每次导航到此路由时发出新的数据请求,也可以缓存数据并在每次后续访问路由时将数据提供给 TeamComponent。

查看此示例应用,其中说明了解析程序防护的一般用法:https://github.com/Farata/angulartypescript/tree/master/code-samples/chapter4/router-advanced-samples/src/app/resolver。

但是,如果要实现带有缓存的可注入服务,请查看data.resolver2.ts和data.service.ts中的代码。

相关内容

最新更新