I'm struggling with retaining data after refreshing a page. My approach involves using a shared service to transfer data between unrelated components. Despite extensive research on LocalStorage implementation and usage, I have not been able to find a suitable solution for my project due to the multitude of options available. I have a course-detail component that passes the course ID to the service, and a course-play component that retrieves this ID and makes an HTTP request using it. However, every time I refresh the course-play page, the data disappears. I need guidance on utilizing LocalStorage effectively to persist this data across refreshes (and updating the ID when switching to a different course). I will include the relevant code snippets below:
course.service
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { Observable, throwError } from 'rxjs';
import { catchError, groupBy } from 'rxjs/operators';
import { ICourse } from './course';
// Inject Data from Rails app to Angular app
@Injectable()
export class CourseService{
// JSON url to retrieve data from
private url = 'http://localhost:3000/courses';
private courseUrl = 'http://localhost:3000/courses.json';
// Subscribing to data
private courseId = new BehaviorSubject(1);
public courseId$ = this.courseId.asObservable();
// Updating the observable value
setId(courseId) {
this.courseId.next(courseId)
}
constructor(private http: HttpClient) { }
// Error handling method
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
}
else {
console.error(
'Backend returned code ${error.status}, ' +
'body was ${error.error}');
}
return throwError('Something went wrong; please try again later.');
}
// Fetching all courses from Rails API App
getCourses(): Observable<ICourse[]> {
const coursesUrl = `${this.url}` + '.json';
return this.http.get<ICourse[]>(coursesUrl)
.pipe(catchError(this.handleError));
}
// Fetching a single course by id
getCourse(id: number): Observable<ICourse> {
const detailUrl = `${this.url}/${id}` + '.json';
return this.http.get<ICourse>(detailUrl)
.pipe(catchError(this.handleError));
}
}
course-detail.component
import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';
import { ActivatedRoute, Router, Routes } from '@angular/router';
import { ICourse } from '../course';
import { CourseService } from '../course.service';
@Component({
selector: 'lg-course-detail',
templateUrl: './course-detail.component.html',
styleUrls: ['./course-detail.component.sass']
})
export class CourseDetailComponent implements OnInit {
course: ICourse;
errorMessage: string;
constructor(private courseService: CourseService,
route: ActivatedRoute,
router: Router) {
}
ngOnInit() {
const id = + route.snapshot.paramMap.get('id');
courseService.setId(id);
getCourse(id);
}
getCourse(id: number) {
courseService.getCourse(id).subscribe(
course => this.course = course,
error => this.errorMessage = <any>error
);
}
}
course-play.component
import { Component, OnInit, Input} from '@angular/core';
import { ActivatedRoute, Router, Routes, NavigationEnd } from '@angular/router';
import { MatSidenavModule } from '@angular/material/sidenav';
import { ICourse } from '../course';
import { CourseService } from '../course.service';
@Component({
selector: 'lg-course-play-course-play',
templateUrl: './course-play.component.html',
styleUrls: ['./course-play.component.sass']
})
export class CoursePlayComponent implements OnInit {
errorMessage: string;
course: ICourse;
courseId: number;
constructor(private courseService: CourseService,
route: ActivatedRoute,
router: Router) {
courseService.courseId$.subscribe( courseId => {
this.courseId = courseId;
})
}
ngOnInit() {
const segment_id = + route.snapshot.paramMap.get('segment_id');
console.log(courseId);
getCourse(courseId);
}
getCourse(id: number) {
console.log(id);
courseService.getCourse(id).subscribe(
course => this.course = course,
error => this.errorMessage = <any>error
);
}
}