尝试从 service.ts angular 调用时,观察者函数在应用程序组件中不起作用

Observer funtion is not working in app-component when trying to call it from service.ts angular

我创建了一个响应式侧边菜单,它在应用程序内组件中运行良好,但是当我尝试将该功能移动到我的 service.ts 文件时,它根本无法运行。以下代码适用于我的 app.component.ts

import { Component} from '@angular/core';
import { MyDataServiceService } from './my-data-service.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    title = 'azad-app';
    name = '';
    
    constructor(private user: MyDataServiceService) { }
    
    ngAfterViewInit() {
        this.user.menuDisplay();
    }
}

这是我在service.ts

中的函数代码
import { Injectable, ViewChild } from '@angular/core';
import { MatSidenav } from '@angular/material/sidenav';
import { BreakpointObserver } from '@angular/cdk/layout';

@Injectable({
    providedIn: 'root'
})
export class MyDataServiceService {

    @ViewChild(MatSidenav)
    sidenav!: MatSidenav;

    constructor(private observer: BreakpointObserver,) { }

    menuDisplay() {
        this.observer.observe(['(max-width:800px)']).subscribe((res) => {
            if (res.matches) {
                this.sidenav.mode = 'over';
                this.sidenav.close();
            } else {
                this.sidenav.mode = "side";
                this.sidenav.open();
            }
        });
    }
}

您应该创建指令而不是使用服务。像这样:

@Directive({selector: 'mat-sidenav[appMenu]'})
export class AppMenu implements OnDestroy{
  private readonly subscription = this.observer.observe(['(max-width:800px)']).subscribe((res) => {
        if (res.matches) {
            this.sidenav.mode = 'over';
            this.sidenav.close();
        } else {
            this.sidenav.mode = "side";
            this.sidenav.open();
        }
    });
  constructor(private readonly sidenav: MatSidenav, private readonly observer: BreakpointObserver){ } 

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }
}

Angular 可以将 componenet 注入到指令中,使用这种方法你可以将你的 sidenav 逻辑封装到一个单独的 class.