저는 Angular 2와 Typescript에 익숙하지 않습니다. 생성자와 ngOnInit을 사용하여 새로 고침하고 있습니다.ngOnInit에서 서비스 메소드에 액세스하는 방법은 무엇입니까?
나는 다음에 생성자에서 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에서 동일한 작업을 수행하는 방법을 알고 싶습니다.