使用LocalStorage的Angular 6 BehaviorSubject

时间:2018-08-05 09:34:05

标签: angular typescript local-storage httpclient behaviorsubject

刷新页面后保存数据时出现问题。我正在使用共享服务在不相关的组件之间传递数据。我在所有Google上搜索了有关LocalStorage以及如何使用它的信息,但没有得到答案。 LocalStorage有很多不同的实现方式,我不知道什么适合我的项目。 我有将课程ID传递给服务的课程细节组件,以及获得该ID并请求使用该ID请求http获取的Course-Play组件。每次刷新课程页面时,数据都会消失。我需要编写什么内容以及在刷新后使用LocalStorage在何处保存此数据时需要帮助(并在其他课程中更新ID)。 我将附上相关代码:

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 get data from
  private url = 'http://localhost:3000/courses';
  private courseUrl = 'http://localhost:3000/courses.json';

  // Subscribe data
  private courseId = new BehaviorSubject(1);
  public courseId$ = this.courseId.asObservable();

  // here we set/change value of the observable
  setId(courseId) {
    this.courseId.next(courseId)
  }

  constructor(private http: HttpClient) { }

  // Handle Any Kind of Errors
  private handleError(error: HttpErrorResponse) {

    // A client-side or network error occured. Handle it accordingly.
    if (error.error instanceof ErrorEvent) {
      console.error('An error occured:', error.error.message);
    }

    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong.
    else {
      console.error(
        'Backend returned code ${error.status}, ' +
        'body was ${error.error}');
    }

    // return an Observable with a user-facing error error message
    return throwError(
      'Something bad happend; please try again later.');
  }

  // Get All Courses from Rails API App
  getCourses(): Observable<ICourse[]> {
  const coursesUrl = `${this.url}` + '.json';

  return this.http.get<ICourse[]>(coursesUrl)
      .pipe(catchError(this.handleError));
  }

  // Get Single Course by id. will 404 if id not found
  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';


// Course-detail decorator
@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,
        private route: ActivatedRoute,
        private router: Router) {
  }

  // On start of the life cycle
  ngOnInit() {
    // get the current course id to use it on the html file
    const id = +this.route.snapshot.paramMap.get('id');

    // set curretn course Id in the service to use it later
    this.courseService.setId(id);
    this.getCourse(id);
    }

    // Get course detail by id
    getCourse(id: number) {
        this.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';


// Couse-play decorator
@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,
      private route: ActivatedRoute,
      private router: Router) {
         courseService.courseId$.subscribe( courseId => {
           this.courseId = courseId;
         })
    }

    // On start of the life cycle
    ngOnInit() {
        // get the current segment id to use it on the html file
        const segment_id = +this.route.snapshot.paramMap.get('segment_id');

        console.log(this.courseId);
        this.getCourse(this.courseId);
      }


      // Get course detail by id
      getCourse(id: number) {
          console.log(id);
          this.courseService.getCourse(id).subscribe(
            course => this.course = course,
            error  => this.errorMessage = <any>error
          );
        }

}

2 个答案:

答案 0 :(得分:1)

首先,您在this.files.reverse()方法中遇到错误-它必须以课程ID的值作为参数,而不是主题。

您需要在主题上调用setId()之后立即更新本地存储,然后从服务的构造函数中的存储中重新加载保存的数据。例如,

next()

答案 1 :(得分:0)

您可以通过以下方式将数据保存到本地存储中:

localStorage.setItem('variablename',JSON.stringify('您要保存的数据'));

并通过以下方法从本地存储中获取数据:

this.anyvariable = JSON.parse(localStorage.getItem('savedvariablename'));

有关本地存储的信息就是这样: