because some object like localstorage, window use in client side are not defined in server side you must first check your browser platform is ready then work with these objectes
for this you can do like:
at first generate check-is-browserService.service.ts like this:
export class CheckIsBrowserService {
private isBrowser = new BehaviorSubject<boolean>(null);
constructor() {}
getIsBrowser(): Observable<any> {
return this.isBrowser;
}
setIsBrowser(value: any) {
this.isBrowser.next(value);
}
}
app.component.ts
constructor(
@Inject(PLATFORM_ID) private platformId: any,
private checkIsBrowserService: CheckIsBrowserService
){
this.checkIsBrowserService.setIsBrowser(isPlatformBrowser(platformId));
}
then generate service for example window.service.ts
class Window implements Window {
readonly innerWidth: number;
}
@Injectable({
providedIn: 'root',
})
export class WindowService {
private config: Window;
constructor(private checkIsBrowserService: CheckIsBrowserService) {
this.config = new Window();
this.checkIsBrowserService.getIsBrowser().subscribe((isBrowser) => {
if (isBrowser) {
this.config = window;
}
});
}
innerWidth() {
return this.config.innerWidth;
}
}
and when in your component use window.innerwidth you must change it to
x.component.ts:
constructor(private window: WindowService) {
if (this.window.innerWidth() <= 1024) {
//your code
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…