我有两个组件之间共享的服务,我将ElementRef从第二个(子)传递给第一个组件(父级) - 一切似乎都没问题,但是一旦我尝试调用例如scroller.nativeElement我得到这个例外: EXCEPTION:错误:未捕获(在承诺中):TypeError:_this.scroller为null
// this is working
this.repositionSubscription = this.sharedService.repositionAction$.subscribe(scrollable => {
console.log('resize');
console.log(scrollable);// here looks ok, firebug gives me nice element
});
但是一旦我改为
// this is not working
this.repositionSubscription = this.sharedService.repositionAction$.subscribe(scrollable => {
console.log('resize');
scrollable.nativeElement.whatever();
});
我不知道怎么可能? 如果我省略服务(就像我第一次做的那样)并尝试这样做,就会出现类似的问题:
this.scroller = this.dialog.nativeElement.querySelector('paper-dialog-scrollable');
console.log(this.scroller); // works fine
this.scroller = this.dialog.nativeElement.querySelector('paper-dialog-scrollable');
this.scroller.nativeElement.whatever(); // not working, exception as above
//编辑以提供更多信息, 父控制器
export class UserDetailComponent implements OnInit, OnDestroy {
private sub: any;
public id: number;
@ViewChild('dialog') dialog: any;
private scroller: ElementRef;
private repositionSubscription:Subscription;
constructor(
private router: Router,
private sharedService: SharedService,
private route: ActivatedRoute
) {
}
ngOnInit() {
console.log('User Detail Component Init');
this.sub = this.route.params.subscribe(params => {
this.id = +params['id'];
this.dialog.nativeElement.open();
});
this.repositionSubscription = this.sharedService.repositionAction$.subscribe(scrollable => {
//Reposition paper dialog
scrollable.nativeElement.dialogElement =this.dialog.nativeElement; // error, scrollable is null, but with commenting that line, and doing console.log(scrollable) i get proper element, only when i try to use that variable my app is throwing exception as described before
this.dialog.nativeElement.notifyResize();
});
}
子组件只是让@ViewChild可滚动并使用this.sharedService.repositionDialog(this.scrollable);
和共享服务看起来像这样:
@Injectable()
export class SharedService {
// Observable navItem source
private reposition = new BehaviorSubject<ElementRef>(null);
// Observable navItem stream
repositionAction$ = this.reposition.asObservable();
// service command
repositionDialog(scrollable:ElementRef) {
this.reposition.next(scrollable);
}
}
首先,我试图获得该嵌套组件的ViewChild / ContentChild,但我无法让它工作。组件被加载到路由器插座,所以也许这就是为什么?我认为这是最干净的方式,但是因为我无法让它工作我尝试了服务 - 仍然不能正常工作。 谢谢你的帮助