简体   繁体   中英

getting error when reloading page in Angular

i have a list of decks, when i click on a deck the proper deck-detail component is loaded showing the details of the deck selected and the Url becomes deck/id/deckName. But when i reload the page or if i try to copy the url of a specific deck i get this error:

Cannot read property 'deckName' of undefined

i think i'm doing something wrong in the routing, this is deck-details component

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(); }


}

and 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>

this is the app routing module

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 { }

In your html file add a condition if deck is available or not.

<div class="container" *ngIf="deck">

as this is undefined when page load

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM