如何在ngOnInit中访问服务方法?

时间:2017-12-29 18:59:32

标签: angular typescript angular-material2

我是Angular 2和Typescript的新手,我正在使用构造函数和ngOnInit进行实现。

from this stackblitz example

为什么我可以在下面的构造函数中使用matchMedia

import {MediaMatcher} from '@angular/cdk/layout';
import {ChangeDetectorRef, Component} from '@angular/core';

/** @title Responsive sidenav */
@Component({
  selector: 'sidenav-responsive-example',
  templateUrl: 'sidenav-responsive-example.html',
  styleUrls: ['sidenav-responsive-example.css'],
})
export class SidenavResponsiveExample {
  mobileQuery: MediaQueryList;

  private _mobileQueryListener: () => void;

  constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher) {
    this.mobileQuery = media.matchMedia('(max-width: 600px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

但是当我尝试在ngOnInit中使用matchMedia时,我得到ERROR TypeError: layout_1.MediaMatcher.matchMedia is not a function

import {MediaMatcher} from '@angular/cdk/layout';
import {ChangeDetectorRef, Component, OnInit} from '@angular/core';

/** @title Responsive sidenav */
@Component({
  selector: 'sidenav-responsive-example',
  templateUrl: 'sidenav-responsive-example.html',
  styleUrls: ['sidenav-responsive-example.css'],
  providers: [MediaMatcher]
})
export class SidenavResponsiveExample implements OnInit {
  mobileQuery: MediaQueryList;
  mobileQuery = {matches:false};
  foo: MediaMatcher;


  private _mobileQueryListener: () => void;

  ngOnInit() {
    this.mobileQuery = MediaMatcher.matchMedia('(max-width: 600px)');
    this._mobileQueryListener = () => ChangeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

我知道构造函数用于初始化,并且比ngOnInit更合适。我只是在试验,并想知道如何在ngOnInit中做同样的事情。

2 个答案:

答案 0 :(得分:1)

您需要在构造函数中注入dependecny(使用访问修饰符),然后使用this

访问该属性

<强> Demo

 constructor(private changeDetectorRef: ChangeDetectorRef,private media: MediaMatcher) {

      }
    ngOnInit(){
      this.mobileQuery = this.media.matchMedia('(max-width: 600px)');
        this._mobileQueryListener = () => this.changeDetectorRef.detectChanges();
        this.mobileQuery.addListener(this._mobileQueryListener);
    }
      ngOnDestroy(): void {
        this.mobileQuery.removeListener(this._mobileQueryListener);
      }

      shouldRun = [/(^|\.)plnkr\.co$/, /(^|\.)stackblitz\.io$/].some(h => h.test(window.location.host));
    }

答案 1 :(得分:0)

您需要通过构造函数注入MediaMatcher并使用this

调用它
constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher) {
    this.mobileQuery = media.matchMedia('(max-width: 600px)');
    this._mobileQueryListener = () => changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

  ngOnInit() {
    this.mobileQuery = this.media.matchMedia('(max-width: 600px)'); // use this
    this._mobileQueryListener = () => ChangeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }