Компонент Angular 2 не перемещается к другому компоненту
Я новичок в Angular, разрабатываю кроссплатформенное приложение для настольных компьютеров в Electron. Пока экзамен сдан, компонент не перемещается к компоненту результата, но когда я щелкаю где-то еще в представлении, он перемещается к другому компоненту.
Вот мой код для отправки:
submit() {
try {
if(this.sub != null){
this.sub.unsubscribe();
}
this._dataService.examConfigurationModel = this.examConfigurationModel;
this._router.navigate(['resultpanel']);
alert('Navigation performed');
}
catch (Error) {
console.log(JSON.stringify(Error.message))
alert(Error.message);
}
}
И вот у меня есть мой App.routes
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home.component';
import { LoginComponent } from './components/auth/login.component';
import { VerifyComponent } from './components/auth/verify.component';
import { RegisterComponent } from './components/auth/register.component';
import { LanguageComponent } from './components/preference/language.component';
import { QualificationComponent } from './components/preference/qualification.component';
import { CategoriesComponent } from './components/preference/categories.component';
import { NewsComponent } from './components/news/news.component';
import { ExamComponent } from './components/exam/exam.component';
import { ExamCategoryComponent } from './components/exam/exam_category.component';
import { BookHomeComponent } from './components/book/home.component';
import { BookBaseComponent } from './components/book/base.component';
import { BookCategoryComponent } from './components/book/book_category.component';
import { JobComponent } from './components/job/job.component';
import { DetailsComponent } from './components/book/details.component'
import { BookPdfComponent } from './components/book/pdf.component'
import { ExamBaseComponent } from './components/exam/base.component'
import { MyExamComponent } from './components/exam/my_exam.component'
import { ExamDetailsComponent } from './components/exam/details.component'
import { resultComponent } from './components/exam/result.component'
import { ResultDetailComponent } from './components/exam/result_detail.component'
import { topfreeComponent } from './components/exam/topfree.component'
import { ExamPanelComponent } from './components/exam/exampanel.component'
import { ResultPanelComponent } from './components/exam/resultpanel.component'
import { JobDetailssComponent } from './components/job/details.component'
import { JobBaseComponent } from './components/job/base.component';
import { SavedJobs } from './components/job/savedjob.component';
import { SavedJobDetails } from './components/job/savedjob.details.component';
import { SuggestedComponent } from './components/book/suggested.component';
import { BookLanguageComponent } from './components/book/languagebook.component';
import { MyInstitutes } from './components/preference/myinstitutes.component';
import { forgetComponent } from './components/auth/forgetPass.component'
import { ExplanationPanel } from './components/exam/explanationpanel.component'
import { savePreference } from './components/auth/savePreference.component'
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'verify', component: VerifyComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'forgetpassword', component: forgetComponent },
{ path: 'readBook', component: BookPdfComponent },
{ path: 'exampanel', component: ExamPanelComponent },
{ path: 'resultpanel', component: ResultPanelComponent },
{ path: 'explanationpanel', component: ExplanationPanel },
{
path: 'home', component: HomeComponent, children: [
{ path: '', redirectTo: 'news', pathMatch: 'full' },
{ path: 'language', component: LanguageComponent },
{ path: 'qualification', component: QualificationComponent },
{ path: 'categories', component: CategoriesComponent },
{ path: 'myinstitutes', component: MyInstitutes },
{ path: 'savepreferences', component: savePreference },
{ path: 'news', component: NewsComponent },
{
path: 'book', component: BookBaseComponent, children: [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{
path: 'home', component: BookHomeComponent, children: [
{ path: '', redirectTo: 'suggestedBooks', pathMatch: 'full' },
{
path: 'suggestedBooks', component: SuggestedComponent, children: [
{ path: 'details', component: DetailsComponent }
]
},
{
path: 'languagesBooks', component: BookLanguageComponent, children: [
{ path: 'detailsofbook', component: DetailsComponent }
]
}
]
},
{
path: 'bookmore', component: BookCategoryComponent, children: [
{ path: 'details', component: DetailsComponent }
]
}
]
},
{
path: 'exam', component: ExamBaseComponent, children: [
{ path: '', redirectTo: 'suggested', pathMatch: 'full' },
{
path: 'suggested', component: ExamComponent, children: [
{ path: 'examDetails', component: ExamDetailsComponent }
]
},
{
path: 'myexams', component: MyExamComponent, children: [
{ path: 'examDetailsMyExams', component: ExamDetailsComponent }
]
},
{
path: 'myResult', component: resultComponent, children: [{
path: 'resultDetail', component: ResultDetailComponent
}
]
},
{
path: 'topFree', component: topfreeComponent, children: [
{ path: 'topFreeDetails', component: ExamDetailsComponent }
]
},
{ path: 'moreExams', component: ExamCategoryComponent }
]
},
{
path: 'job', component: JobBaseComponent, children: [
{ path: '', redirectTo: 'jobhome', pathMatch: 'full' },
{
path: 'jobhome', component: JobComponent, children: [
{ path: 'jobdetails', component: JobDetailssComponent }
]
},
{
path: 'savedjobs', component: SavedJobs,
children: [
{ path: 'savejobdetails', component: SavedJobDetails }
]
}
]
}
]
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { useHash: true })
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
export const routingComponenets = [LoginComponent,
HomeComponent,
VerifyComponent,
RegisterComponent,
LanguageComponent,
QualificationComponent,
CategoriesComponent,
NewsComponent,
ExamComponent,
ExamCategoryComponent,
BookHomeComponent,
BookBaseComponent,
BookCategoryComponent,
DetailsComponent,
JobComponent,
BookPdfComponent,
ExamBaseComponent,
MyExamComponent,
ExamDetailsComponent,
resultComponent,
ResultDetailComponent,
topfreeComponent,
ExamPanelComponent,
ResultPanelComponent,
JobBaseComponent,
JobDetailssComponent,
SavedJobs,
SavedJobDetails,
SuggestedComponent,
BookLanguageComponent,
MyInstitutes,
forgetComponent,
ExplanationPanel,
savePreference]
и приложения
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
/*
* Angular Modules
*/
import { enableProdMode, NgModule, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { RouterModule, Router } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './components/app.component';
import { SearchFilterPipe } from './pipes/SearchFilterPipe'
import { FileSizePipe } from './pipes/FileSizePipe'
import { AppRoutingModule, routingComponenets } from './app.routes';
import { PdfViewerComponent } from 'ng2-pdf-viewer';
import{PdfViewerServices} from './services/pdfViewer'
import{DataService} from './services/data.service';
import { ChartsModule } from 'ng2-charts/ng2-charts';
import Chart from 'chart.js';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
BrowserAnimationsModule,
AppRoutingModule,
ChartsModule
],
declarations: [
SearchFilterPipe,
FileSizePipe,
AppComponent,
routingComponenets,
PdfViewerComponent],
bootstrap: [AppComponent],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
],
providers:[PdfViewerServices,DataService]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
2 ответа
this._router.navigate(['resultpanel']);
должно быть как:
this._router.navigate(['/resultpanel']);
Обратите внимание на косую черту в приведенном выше примере.
На Angular доступны два метода Router
класс для обязательной навигации в ваших классах компонентов: Router.navigate
а также Router.navigateByUrl
,
navigateByUrl()
- Требуется абсолютный путь.
navigate()
- Требуется относительный путь
В вашем случае кажется, что вы используете относительный путь маршрутизации. Таким образом, вы должны изменить свой код и добавить косую черту /
относительный путь.
Я изменил ваш код.
submit() {
try {
if(this.sub != null){
this.sub.unsubscribe();
}
this._dataService.examConfigurationModel = this.examConfigurationModel;
this._router.navigate ([ '/ resultpanel']);
alert('Navigation performed');
}
catch (Error) {
console.log(JSON.stringify(Error.message))
alert(Error.message);
}
}