Angular 17 本地存储

问题描述 投票:0回答:2

我已经尝试了许多使用 localStorage 的教程,但无论我做什么,我都会发现 localStorage 未定义。 Angular 17 的 localStorage 似乎与旧版本不同。下面是我的两个部分,但我找不到有关使用 localStorage 的 Ang17 教程

本地.token.ts

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'

})
export class LocalService {
  name = "Das Hotel";
  
  constructor() {   }

  public saveData(key: string, value: string) {
    localStorage.setItem(key, value);
  }
  public getData(key: string) {
    return localStorage.getItem(key)
  }
  public removeData(key: string) {
    localStorage.removeItem(key);
  }
  public clearData() {
    localStorage.clear();
  }
}

app.component.ts

import { AfterViewInit, Component, ElementRef, Inject, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { RoomsComponent } from './rooms/rooms.component';
import { RoomsListComponent } from './rooms/rooms-list/rooms-list.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HeaderComponent } from './header/header.component';
import { ContainerComponent } from './container/container.component';
import { EmployeeComponent } from './employee/employee.component';
import { APP_CONFIG, APP_SERVICE_CONFIG } from './AppConfig/appconfig.service';
import { LocalService } from './local.token';
import { HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'hinv-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet,NgbModule,RoomsComponent, 
    RoomsListComponent, HeaderComponent, ContainerComponent, EmployeeComponent,
    HttpClientModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
  providers: [{
    provide: APP_SERVICE_CONFIG,
    useValue: APP_CONFIG,
  }]
})

export class AppComponent implements OnInit {
  title = 'hotelapp';
  @ViewChild('name', {static: true}) name!: ElementRef;
  constructor(private localStore: LocalService) {}

  ngOnInit(): void {
    this.name.nativeElement.innerText = "Huff's Hotel";
    this.localStore.saveData('name','Huff Hotel');
    this.localStore.getData('name');
  }
}



尝试了不同的教程和论坛建议

angular
2个回答
2
投票

您遇到了 SSR 问题。

LocalStorage
是仅限浏览器的功能。

您只能通过禁用 SSR 来运行应用程序客户端:

删除

prerender:true
以及
server
 中的 
angular.json

条目

0
投票

如果您想使用 SSR 并使用本地存储,请检查 paltform 并将本地存储分配给变量。

private readonly storage!: Storage;
if (this.platform.isBrowser && window?.localStorage) {
  this.storage = window.localStorage;
}
© www.soinside.com 2019 - 2024. All rights reserved.