【问题标题】:Angular 2 - Load route component and then gets back to previous componentAngular 2 - 加载路由组件,然后返回到前一个组件
【发布时间】:2017-05-29 08:16:53
【问题描述】:

我对 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>

最后,我从参数“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,但返回 /teams 方向(并且不打印团队列表)。我试图更改路线名称(例如 /detail/:id),但仍然无法正常工作。有什么建议么?提前致谢。

【问题讨论】:

  • 路线“teams”第一次是否有效?
  • 您的 TeamService 看起来如何?
  • 是的@MarkusKollers,当我第一次进入“/teams”时,它会打印正确的列表。
  • 我已经构建了一个干净的 angular-cli 项目并添加了您的组件和服务,并且它可以工作。您的开发者控制台 (F12) 中是否出现任何错误?
  • @MarkusKollers 它说属性绑定字段为空(错误错误:未捕获(在承诺中):TypeError:无法读取 null 的属性“名称” TypeError:无法读取 Object 处的 null 属性“名称” .eval [as updateRenderer] (TeamComponent.html:5) at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:12822))。就像路由 /team/19 (例如)不起作用,它试图在 /teams 上渲染 TeamComponent。事实上,在 Chrome 调试器的网络部分,/team/19 永远不会被调用。非常非常奇怪。

标签: javascript angular angular2-routing angular2-services


【解决方案1】:

好的,知道了。您的请求将被异步执行,因此在您的组件创建时,团队为空。我认为您的 TeamComponent 中有这样的绑定:

{{ team.name }}

如果团队为空,则无法访问名称并崩溃。为确保 html 将正确呈现,请使用 elvis-operator,如下所示:

{{ team?.name }}

这只会在团队不为空或未定义时访问名称

【讨论】:

  • 就是这样。多么愚蠢的初学者错误:(非常感谢马库斯。吸取的教训。
【解决方案2】:

更新: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);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2017-01-13
    • 2018-03-20
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多