Issue
I've tried numerous tutorials to use localStorage but no matter what I do, I get localStorage is not defined. It appears that Angular 17 does localStorage different that older versions. The below is my two sections but I can't find an Ang17 tutorial on using localStorage
local.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');
}
}
tried different tutorials and forum suggestions
Solution
You have a SSR issue. LocalStorage
is a browser only feature.
You can run the app client side only by disabling SSR with:
Remove prerender:true
and the server
entry in angular.json
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.