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

时间:2018-05-13 10:56:09

标签: angular angular5 ngoninit

我有这个基本的应用程序,我从一个带有数据服务的firestore中获取数据。我有几个页面(组件),团队,球员,统计......

例如我的团队成员:



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);
  }
}
&#13;
&#13;
&#13;

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

看看这个示例应用程序,它说明了解析器警卫的一般用法:https://github.com/Farata/angulartypescript/tree/master/code-samples/chapter4/router-advanced-samples/src/app/resolver

但是如果你想用缓存实现一个可注入服务,请看一下data.resolver2.ts和data.service.ts中的代码。