Angular 2 - 加载路径组件,然后返回上一个组件

时间:2017-05-29 08:16:53

标签: javascript angular angular2-routing angular2-services

我对Angular 2路由有问题。当我点击我的链接获取团队详细信息时,它采用正确的路线并加载指定的组件(TeamComponent)。但是,立即“回到”前一个组件(TeamsComponent),这是团队列表。

这是我项目的结构:

/app
|_shared
   |_team
      |_team.component.css
      |_team.component.html
      |_team.component.ts
      |_team.model.ts
      |_team.service.ts
   |_team-list
      |_team-list.component.css
      |_team-list.component.html
      |_team-list.component.ts
|_teams
   |_teams.component.css
   |_teams.component.html
   |_teams.component.ts
   |_teams.module.ts
   |_teams-routing.module.ts

首先,我在 teams-routing.module.ts 上设置路线:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { TeamsComponent } from './teams.component';
import { TeamComponent } from '../shared/team/team.component';

const teamsRoutes: Routes = [
  {
    path: 'team/:id',
    component: TeamComponent
  },{
    path: 'teams',
    component: TeamsComponent
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(teamsRoutes)
  ]
})
export class TeamsRoutingModule { }

teams.component.ts 上的teamService加载团队列表,并将其发送到 teams.component.html 上的团队列表:

import { Component, OnInit } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';

import { TeamService } from '../shared/team/team.service';
import { Team } from '../shared/team/team.model';

@Component({
  selector: 'app-teams',
  templateUrl: './teams.component.html',
  styleUrls: ['./teams.component.css']
})
export class TeamsComponent implements OnInit {

  teamList: Team[] = [];

  constructor(private teamService: TeamService) { }

  ngOnInit() {
    this.teamService.getTeams().subscribe(teams => {
      Observable.from(teams).subscribe(team => {
        this.teamList.push(team);
      });
    });
  }

}

teams.component.html

<section class="teams">
  <app-team-list [teams]="teamList"></app-team-list>
</section>

然后,通过我的团队列表,我在 team-list.component.html 上设置HTML列表:

<section *ngFor="let team of teams" class="team_list">
  <div class="card" style="width: 20rem;">
    <img class="card-img-top" src="/assets/logos/{{team.logo}}" alt="Team Logo">
    <div class="card-block">
      <h4 class="card-title">{{team.name}}</h4>
      <p class="card-text">{{team.location}}</p>
      <a routerLink="/team/{{team.id}}" class="btn btn-primary">Team Info</a>
    </div>
  </div>
</section>

最后,我从param“id”获取团队信息,并在 team.component.ts 中获取服务:

import { Component, Input, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Team } from './team.model';
import { TeamService } from "./team.service";
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-team',
  templateUrl: './team.component.html',
  styleUrls: ['./team.component.css']
})
export class TeamComponent implements OnInit {

  team: Team = null;

  constructor(private teamService: TeamService,
              private activatedRoute: ActivatedRoute,
              private router: Router
  ) {}

  ngOnInit() {
    let teamId: number = this.activatedRoute.snapshot.params['id'];

    console.log("Vamos a buscar el equipo");
    this.teamService.getTeamById(teamId).subscribe(team => this.team = team);
  }

}

它使用团队数据加载TeamComponent HTML,但返回/团队方向(并且不打印团队列表)。我试图更改路由名称(例如/ detail /:id),但仍然无效。有什么建议?提前谢谢。

2 个答案:

答案 0 :(得分:1)

好的,明白了。您的请求将被退出异步,因此在组件的创建时,团队为空。我认为你的TeamComponent中有这样的绑定:

library(data.table)
dt_results<-fread("test2.csv") #just reading the data
dt_results[,c("EventDate","CaseDate"):=list(as.Date(EventDate),as.Date(CaseDate))]
dt_results[,Period:=as.numeric(ceiling((EventDate-CaseDate+1)/5))] #constructing your period variable
dt_results[, sum(Value),by=c("ID","Period", "Etype")] #sum and group

如果team为null,则无法访问名称并且崩溃。为了确保html的呈现没有错误,请使用elvis-operator,如下所示:

{{ team.name }}

如果团队不为null或未定义,则只会访问名称

答案 1 :(得分:0)

更新:getTeamById服务

getTeamById(id: number): Observable<Team> {

    let team: Team = null;

    return this.http.get(this.urlTeams+'/'+id)
      .map(response => {
        let dbTeam: any = response.json();
        for(let i in dbTeam) {
          team = new Team(dbTeam[i].teamId,dbTeam[i].teamName,dbTeam[i].teamLocation,dbTeam[i].teamFoundation,dbTeam[i].teamDivision,dbTeam[i].teamConference,dbTeam[i].teamStadium,dbTeam[i].teamAttendance,dbTeam[i].teamLogo,dbTeam[i].teamStadiumPhoto);
        }
        return team;
      })
      .catch(this.handleError);
  }