Reputation: 521
I have two components:
Semester-planning:
onSubmit(student: Student) {
this.studentService.postStudent(student).subscribe((s) => {
this.router.navigate(['home-page/semester-planning/classes-planning/' + s.id]);
});
}
And classes-planning, which is redirected from semester-planning, that fetch the student by id and then display the info:
ngOnInit(): void {
this.studentId = this.route.snapshot.paramMap.get('id');
}
ngAfterViewInit(): void {
this.getStudent().subscribe(student => {
this.dateProcessed = this.processDate(student.startDate, student.endDate);
})
}
getStudent(): Observable<Student> {
return this.studentService.getStudent(this.studentId);
}
This is the router for both components:
{
path: 'semester-planning',
component: SemesterPlanningComponent,
canActivate: [AuthGuard, StudentGuard],
},
{
path: 'semester-planning/classes-planning/:id',
component: ClassesPlanningComponent,
canActivate: [AuthGuard],
}
This works fine unless the user's already navigated to classes-planning and click to go to semester-planning and they are redirected to that again although already submitted the data.
I would like to prevent redirect to semester-planning if the user already submitted the data and navigated to classes-planning. I tried creating student guard below, but don't know how to check if the student already submitted the data (navigated to classes-planning). Using localStorage would be okay but if the user switches browser then it won't work anymore.
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (
// check if the student submitted the data?
) {
this.router.navigate(['home-page/semester-planning/classes-planning/']);
return false;
}
return true;
}
Code from student-service that interacts with server (if that's convenient):
getStudent(id: String): Observable<Student> {
const student = this.http.get<Student>(environment.baseUrl + "/api/student/" + id);
return student;
}
postStudent(student: Student): Observable<any> {
return this.http.post(environment.baseUrl + "/api/student", student);
}
I would really appreciate some help.
Upvotes: 0
Views: 51
Reputation: 194
Angular doesn't save the stats when the app reloaded or when accessed directly from the URL that's why you have to use routerlink attribute on the <a>
tag to navigate. I don't know if you are using routerlink or href.
This is not the actual issue but as you said you could use localStorage or you can do validation on the backend (better). I don't know what you meant with "Using localStorage would be okay but if the user switches browser then it won't work anymore."
if you want to save such information in different browsers than you have to save it in the Database.
This Youtube video can help you to know how to persist data in the Angular app Angular 6 Tutorial 19: Persistent Login Session
Upvotes: 1