навигация в Angular 9 викторине не работает - PullRequest
0 голосов
/ 07 марта 2020

У меня возникают трудности с работой навигации между вопросами, см.: https://stackblitz.com/edit/angular-9-quiz-app. При нажатии на следующую кнопку идентификатор вопроса увеличивается на 1, а затем переключается обратно на 1 и не переходит к следующему вопросу. Я получаю это сообщение об ошибке в Chrome Dev Tools:

Ошибка: Uncaught (в обещании): Ошибка: не удается сопоставить ни один маршрут. Сегмент URL: 'question / 2'

Не уверен, что мне не хватает. Он должен работать без использования идентификатора, используя вместо этого индекс quizData. Пожалуйста, не могли бы вы помочь. Спасибо!

В шаблоне di-quiz:

<button type="button" (click)="nextQuestion()">
  Next &raquo;
</button>

позвоните на следующий вопрос в сервисе:

nextQuestion() {
  this.quizService.nextQuestion();
}

в quiz.service.ts :

constructor(
  private timerService: TimerService,
  private router: Router,
  private route: ActivatedRoute) {
    /* this.route.paramMap.subscribe(params => {
      this.setQuestionIndex(+params.get('questionText'));
      this.question = this.getQuestion;
    }); */
}

nextQuestion() {
  this.questionID++;
  this.navigateToNextQuestion();
  this.timerService.resetTimer();
  this.increaseProgressValue();
}

navigateToNextQuestion() {
  this.router.navigate(['/question', this.questionID]);
}

in quiz-routing.module.ts :

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

import { IntroductionComponent } from './containers/introduction/introduction.component';
import { DependencyInjectionQuizComponent } from './containers/dependency-injection-quiz/dependency-injection-quiz.component';
import { ResultsComponent } from './containers/results/results.component';

const routes: Routes = [
  { path: '', redirectTo: 'intro' },
  { path: 'intro', component: IntroductionComponent },
  { path: 'question', component: DependencyInjectionQuizComponent },
  { path: 'question/:questionID', component: DependencyInjectionQuizComponent },
  { path: 'results', component: ResultsComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class QuizRoutingModule {}

и мой объект данных (в quiz.ts ) выглядит так:

export const QUIZ_DATA: Quiz = {
  milestone: 'Dependency Injection Quiz',
  summary: "Dependency Injection is extremely powerful because it is a way of providing dependencies in your code instead of hard-coding them.",
  imageUrl: 'assets/images/DIDiagram.png',
  questions: [
    {
      questionText: 'What is the objective of dependency injection?',
      options: [
        { text: 'Pass the service to the client.', correct: true },
        { text: 'Allow the client to find service.', correct: true },
        { text: 'Allow the client to build service.' },
        { text: 'Give the client part service.' }
      ],
      explanation: 'a service gets passed to the client during DI'
    },
  ...
  ]
};

1 Ответ

3 голосов
/ 29 марта 2020

Существует много проблем с кодом, который я видел. Есть много используемых @Output и @Input. Но большинство из них не имеют значения. Я пытался изменить большинство проблем, но все еще есть немного вещей, которые все еще ожидают. Пожалуйста, посмотрите на репо:

https://github.com/anooprvarrier/Quiz-example

Я обновил все зависимости до последней версии. Пожалуйста, проверьте и дайте мне, если это решило ваши проблемы.

Надеюсь, это поможет

...