-1

我正在解决这个问题,想不出一种方法来处理renderer2.selectRootElement引发的错误。这就是我的函数的样子:

private doSomeAnimation(){
 const modalWrapper = this.renderer2.selectRootElement('.modal-wrapper', true);//It fails here
 // finally do something with modalWrapper
   this.renderer2.addClass(modalWrapper, 'fade-out');
}

如果我打开控制台,我会看到这个错误:

global-angular-error-handler.service.ts:49 Error: The selector ".modal-wrapper" did not match any elements 
at DefaultDomRenderer2.selectRootElement (dom_renderer.ts:146) 
at BaseAnimationRenderer.selectRootElement (animation_renderer.ts:156)
at DebugRenderer2.selectRootElement (services.ts:762)
at ModalComponent.animateClosing (modal.component.ts:39)
....

我还查看了 Renderer2 的文档,并且selectRootElement看起来像这样

selectRootElement(selectOrNode: string|any):any{
  let el: any = typeof selectOrNode === 'string'? document.querySelector(selectOrNode) : selectOrNode;
  if(!el){
    throw new Error(`The selector "${selectorOrNode}" did not match any elements`);
  }
  el.textContent = '';
  return el; 
}

如您所见,我的代码在函数的第 1 行失败,所以我的问题是如果没有任何匹配项,如何在控制台中不显示任何错误。我的意思是如何不在控制台中显示此消息

"The selector ".modal-wrapper" did not match any elements"

有人可以帮助我或指出正确的方向吗?提前非常感谢!

4

1 回答 1

1

您可以将调用包装成 try/catch

let modalWrapper;
try {
    modalWrapper = this.renderer2.selectRootElement('.modal-wrapper', true);
} catch (e) {
    // do what you need to do with the exception here.
    return;
}
于 2020-06-15T23:12:29.770 回答