First this not duplicated take time to read, because there is lot of similar question but they are in the @Component decorator
我有想法在服务中捕获屏幕大小调整然后通过observable共享一些css值,但似乎我的服务无法正常工作(无法捕获屏幕调整大小事件) .
Here is my code
import { Injectable, HostListener } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class BreakPointService {
normal: {
background: 'w3-teal',
inputColor: 'w3-light-grey',
css_parent: 'w3-container w3-teal'
};
breakpoint: {
background: 'w3-dark-blue',
inputColor: 'w3-white',
css_parent: 'w3-container w3-light-grey'
};
breakPointValue: number;
css_behaviour = new BehaviorSubject(JSON.stringify(this.breakpoint));
current_css = this.css_behaviour.asObservable();
@HostListener('window:resize', ['$event'])
onResize(event) {
console.log();
this.breakPointValue = window.innerWidth;
console.log(this.breakPointValue);
if (this.breakPointValue > 768) {
console.log(JSON.stringify(this.normal));
this.css_behaviour.next(JSON.stringify(this.normal));
} else {
console.log(JSON.stringify(this.breakpoint));
this.css_behaviour.next(JSON.stringify(this.breakpoint));
}
}
public css() {
if (this.breakPointValue > 768) {
return this.normal;
}
return this.breakpoint;
}
constructor() { }
}
有什么办法可以做到这一点,或者这是不是可以从服务中获得?
3 回答
感谢所有回复 .
我仍然想要在服务中捕获resise事件,但是感谢@ABOS和一些关于组件通信的教程,我得到了使用root组件来捕获scren size事件然后通过它可观察的变化来提供我的服务的想法,这个所有订阅组件的方式将获得断点css值
这里不再谈论我的实施
app.component
break-point.service
corresponding template
您可能需要查看Angular的Flex-Layout Package . 您可以注入其ObservableMedia服务 . 这将允许您订阅它听取窗口大小的变化 .
每当您调整窗口大小时,都会将媒体更改对象记录到控制台 . 在您的组件中订阅它之后 .
所以我没有在您的OP中看到您正在初始化服务 . 我必须在一个应用程序中完成这个几乎完全的事情 . 我们会监视屏幕大小更改,从而触发本地存储中某些用户首选项的更改:
然后,为了使服务工作,它通过将其注入构造函数参数中的app.component.ts来初始化