首页 文章

如何从角度2的服务获取屏幕调整大小尺寸?

提问于
浏览
2

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 回答

  • 0

    感谢所有回复 .

    我仍然想要在服务中捕获resise事件,但是感谢@ABOS和一些关于组件通信的教程,我得到了使用root组件来捕获scren size事件然后通过它可观察的变化来提供我的服务的想法,这个所有订阅组件的方式将获得断点css值

    这里不再谈论我的实施

    app.component

    import { Component, OnInit, HostListener } from '@angular/core';
    import { BreakPointService } from './providers/break-point.service';
    
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
        title = 'twithashWebApp';
        css_parent = '';
        breakPointValue: number;
        constructor() {
        }
    
        ngOnInit() {
            BreakPointService.current_css.subscribe(value => {
                console.log('value is ' + value);
                this.css_parent = JSON.parse(value).css_parent;
            });
        }
    
        @HostListener('window:resize', ['$event'])
        onResize(event) {
            console.log();
            this.breakPointValue = window.innerWidth;
            console.log(this.breakPointValue);
            if (this.breakPointValue > 768) {
                console.log(JSON.stringify(BreakPointService.normal));
                BreakPointService.css_behaviour.next(JSON.stringify(BreakPointService.normal));
            } else {
                console.log(JSON.stringify(BreakPointService.breakpoint));
                BreakPointService.css_behaviour.next(JSON.stringify(BreakPointService.breakpoint));
            }
        }
    
    
    }
    

    break-point.service

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
        providedIn: 'root',
    })
    export class BreakPointService {
    
        static normal = {
            background: 'w3-teal',
            inputColor: 'w3-light-grey',
            css_parent: 'w3-container w3-teal'
        };
        static breakpoint = {
            background: 'w3-dark-blue',
            inputColor: 'w3-white',
            css_parent: 'w3-container w3-light-grey'
        };
    
    
        static css_behaviour = new BehaviorSubject<string>(JSON.stringify(BreakPointService.breakpoint));
    
        static current_css = BreakPointService.css_behaviour.asObservable();
    
    
    
        constructor() { }
    }
    

    corresponding template

    <!--The content below is only a placeholder and can be replaced.-->
    <div class="{{css_parent}}" style="text-align:center" style="height: 100%">
    <app-tweet-list></app-tweet-list>
    </div>
    
  • 1

    您可能需要查看Angular的Flex-Layout Package . 您可以注入其ObservableMedia服务 . 这将允许您订阅它听取窗口大小的变化 .

    import {MediaChange, ObservableMedia} from '@angular/flex-layout';
    
        @Injectable({
         providedIn: 'root',
        })
        export class BreakPointService {
    
         constructor(media: ObservableMedia) {}
    
         resize(){
          return this.media.pipe(map(change: MediaChange) => {
          //if changes doesn't have the width available on it, access it from the window object
          if (window.innerWidth > 768) {       
                return JSON.stringify(this.normal);
            } else {
                return JSON.stringify(this.breakpoint);
            }
          }));
         }
       }
    

    每当您调整窗口大小时,都会将媒体更改对象记录到控制台 . 在您的组件中订阅它之后 .

  • 0

    所以我没有在您的OP中看到您正在初始化服务 . 我必须在一个应用程序中完成这个几乎完全的事情 . 我们会监视屏幕大小更改,从而触发本地存储中某些用户首选项的更改:

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    import { TableViewTypes, MediaSizes, UserPreferencesDefaults, TableView, getTableViewDefaults } from '../models/user-preferences.model';
    import { StorageService } from './storage.service';
    
    @Injectable()
    export class UserPreferencesService {
    
        private tableViewSubject = new BehaviorSubject<TableView>(UserPreferencesDefaults.tableView);
        tableView$ = this.tableViewSubject.asObservable();
    
        constructor(
            private storageService: StorageService
        ) {}
    
        init() {
            this.tableViewSubject.next(
                !(window.outerWidth > MediaSizes.sm) ?
                getTableViewDefaults(false) :
                UserPreferencesDefaults.tableView
            );
            window.addEventListener('resize', () => {
                this.tableViewSubject.next(
                    !(window.outerWidth > MediaSizes.sm) ?
                    getTableViewDefaults(false) :
                    this.storageService.userPreferences.tableView
                );
            });
        }
    
        storeTableView(tableType: TableViewTypes, value: boolean) {
            this.storageService.userPreferences = {
                ...this.storageService.userPreferences,
                tableView: {
                    ...this.storageService.userPreferences.tableView,
                    [tableType]: value
                }
            };
        }
    
        toggleTableView(tableType: TableViewTypes, value?: boolean) {
            value = value !== undefined && value !== null ? value : !this.storageService.userPreferences.tableView[tableType];
            this.tableViewSubject.next({
                ...this.storageService.userPreferences.tableView,
                [tableType]: value
            });
            this.storeTableView(tableType, value);
        }
    
    }
    

    然后,为了使服务工作,它通过将其注入构造函数参数中的app.component.ts来初始化

    constructor(
        private userPreferenceService: UserPreferencesService,
    ) {this.userPreferenceService.init();}
    

相关问题