Angular ResizeService移动端视图判断的初始值设置问题
解决方案
核心问题是你没有在服务初始化时主动计算当前窗口的尺寸,只会在resize事件触发时更新状态,所以首次加载没有触发resize的情况下只会返回BehaviorSubject的初始默认值false。
修改ResizeService
你不需要从组件传递size参数,服务本身可以直接访问window对象获取初始尺寸,同时把resize事件的监听逻辑移到服务构造函数中,避免多组件调用时产生重复订阅:
import { Injectable } from '@angular/core'; import { BehaviorSubject, fromEvent, Subscription } from 'rxjs'; import { debounceTime, throttleTime } from 'rxjs/operators'; // 按你的需求定义移动端断点,这里宽度设为520px const PHONE_SIZE = { width: 520, height: 900 }; @Injectable({ providedIn: 'root' }) export class ResizeService { private mobileView$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); public mobileViewObs$ = this.mobileView$.asObservable(); private resizeSub?: Subscription; constructor() { // 初始化直接计算当前窗口尺寸,设置首次加载的正确状态 const initSize = { width: window.innerWidth, height: window.innerHeight }; const initIsMobile = this.isMobileView(initSize); this.mobileView$.next(initIsMobile); // 只初始化一次resize监听,不用组件调用方法触发 this.resizeSub = fromEvent(window, 'resize') .pipe(throttleTime(500), debounceTime(500)) .subscribe((resizeEvent: Event) => { const win = resizeEvent.currentTarget as Window; const currentSize = { width: win.innerWidth, height: win.innerHeight }; const isMobile = this.isMobileView(currentSize); this.mobileView$.next(isMobile); }); } private isMobileView(size: {width: number, height: number}): boolean { // 如果只需要判断宽度小于520px,直接用下面这行 return size.width < PHONE_SIZE.width; // 如果要保留原有宽高同时满足的逻辑,替换为下面的代码 // return size.width < PHONE_SIZE.width && size.height < PHONE_SIZE.height; } // root级服务一般不需要手动销毁,需要时可调用该方法取消监听 ngOnDestroy() { this.resizeSub?.unsubscribe(); } }
修改组件代码
不需要再手动调用resizeEvent()方法,也不用在组件里计算初始size,直接订阅服务的observable即可,同时记得添加取消订阅逻辑避免内存泄漏:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; import { BookService } from '你的BookService实际路径'; import { ResizeService } from '你的ResizeService实际路径'; import { BookModel } from '你的BookModel实际路径'; @Component({ selector: 'app-books-list', templateUrl: './books-list.component.html', styleUrls: ['./books-list.component.scss'], }) export class BooksListComponent implements OnInit, OnDestroy { @Input() book!: BookModel; booksArray: BookModel[] = []; oneBook!: BookModel; isMobile: boolean = false; private mobileSub?: Subscription; constructor( private service: BookService, private route: ActivatedRoute, private resizeService: ResizeService ) {} ngOnInit(): void { // 直接订阅即可,服务已经处理了初始值逻辑 this.mobileSub = this.resizeService.mobileViewObs$.subscribe(data => { this.isMobile = data; }); this.service.getBooks().subscribe((books) => { this.booksArray = books; }); } // 组件销毁时取消订阅,避免内存泄漏 ngOnDestroy(): void { this.mobileSub?.unsubscribe(); } }
关键修改说明
- 服务初始化时直接获取当前窗口尺寸计算移动端状态,作为首次推送的值,无需等待resize事件触发
- resize监听逻辑仅在服务初始化时执行一次,避免重复订阅产生性能损耗
- 如果你仅需要判断窗口宽度小于520px就返回true,可以简化
isMobileView方法的判断逻辑,去掉高度判断即可
内容的提问来源于stack exchange,提问作者DoboVlad
相关产品推荐
相关产品推荐

