我有一个牌组列表,当我单击一个牌组时,将加载适当的牌组细节组件,其中显示了所选牌组的详细信息,而Url变成了牌组/ id / deckName。 但是,当我重新加载页面或尝试复制特定卡座的网址时,会出现此错误:
无法读取未定义的属性'deckName'
我认为我在路由中做错了,这是甲板细节组件
import { Card } from "./../../card/card.model";
import { Deck } from "./../../deck/deck.model";
import { Component, OnInit, Input } from "@angular/core";
import { DeckService } from "src/app/deck/deck.service";
import { ActivatedRoute, Params, Router } from "@angular/router";
import { Subscription } from "rxjs";
@Component({
selector: "app-deck-details",
templateUrl: "./deck-details.component.html",
styleUrls: ["./deck-details.component.scss"],
})
export class DeckDetailsComponent implements OnInit {
//@Input() deck: Deck;
paramsSubscription: Subscription;
id: number;
decks: Deck[];
deck: Deck;
constructor(private deckService: DeckService, private route: ActivatedRoute) {
}
ngOnInit() {
this.id = this.route.snapshot.params["id"];
this.paramsSubscription = this.route.params.subscribe((params: Params) => {
this.id = params["id"];
this.decks = this.deckService.getDecks();
this.deck = this.decks.find (
deck => deck.id === this.id
);
});
}
ngOnDestroy() { this.paramsSubscription.unsubscribe(); }
}
和html
<div class="container">
<div class="row">
<div class="deck-details " style="border:solid black">
<h1>{{ deck.deckName }} : {{ deck.deckClass }}</h1>
<div *ngFor="let card of deck.deckCards">
<span
[ngClass]="{
common: card.rarity == 'common',
rare: card.rarity == 'rare',
epic: card.rarity == 'epic',
legendary: card.rarity == 'legendary'
}"
>
{{ card.name }}
</span>
<h4 class="inlineh4">: {{ card.manaCost }} mana</h4>
<img [src]="card.imagePath" alt="" style="height: 20px;" />
</div>
</div>
</div>
</div>
这是应用程序路由模块
const appRoutes: Routes = [
{ path: '', component: CardListComponent },
{ path: 'decks', component: DeckListComponent, children: [
{ path: ':id/:deckName', component: DeckDetailsComponent }
] },
{ path: 'createDeck', component: CreateDeckComponent },
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
答案 0 :(得分:1)
在您的html文件中添加一个条件,确定是否可以使用牌组。
<div class="container" *ngIf="deck">
因为页面加载时未定义