如何摆脱这个黑客 [英] How to get rid of this hack

查看:116
本文介绍了如何摆脱这个黑客的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改类,以便它不使用ApplicationRef。换句话说,如何获取主应用程序不使用应用程序参考。

I want to modify the class so that it does not use the ApplicationRef. In other words how to get hold of main app not using app ref.

@Injectable()
export class ToastsManager {
  container: ComponentRef<any>;
  private options = {
    autoDismiss: true,
    toastLife: 1000
  };
  private index = 0;
  container: ComponentRef<any>;
  private options = {
    autoDismiss: true,
    toastLife: 1000
  };
  private index = 0;

  constructor(private resolver: ComponentResolver,
          private appRef: ApplicationRef,
          @Optional() @Inject(ToastOptions) options) {
    if (options) {
      Object.assign(this.options, options);
    }
  }

  show(toast: Toast) {
    if (!this.container) {
      // a hack to get app element in shadow dom
      let appElement: ViewContainerRef = new     ViewContainerRef_(this.appRef['_rootComponents'][0]._hostElement);

      this.resolver.resolveComponent(ToastContainer)
        .then((factory: ComponentFactory<any>) => {
          this.container = appElement.createComponent(factory);
          this.setupToast(toast);
      });
    } else {
      this.setupToast(toast);
    }
  }

我尝试使用 @ ViewChild ,但它不起作用。

I try with the @ViewChild but it does not work.

推荐答案

您可以使用 ApplicationRef Brandon Roberts在 https://github.com中展示的内容/角/角/问题/ 4112#issuecomment-139381970 ,以获取路由器中引用 CanActivate()

You could do with ApplicationRef what Brandon Roberts demonstrates in https://github.com/angular/angular/issues/4112#issuecomment-139381970 to get a reference to the Router in CanActivate().

可能更好的是共享服务

@Injectable() 
export class Shared {
  appRef = new BehaviorSubject();

  setAppRef(appRef:ApplicationRef) {
    this.appRef.emit(appRef);
  }
}





export class ToastsManager {

  constructor(private resolver: ComponentResolver,
          private appRef: ApplicationRef,
          shared:Shared,
          @Optional() @Inject(ToastOptions) options) {
    shared.setAppRef(appRef);
  }
}





export class OtherClassThatNeedsAppRef {

  constructor(shared:Shared) {
    shared.appRef.subscribe(appRef => this.appRef = appRef);
  }
}

这篇关于如何摆脱这个黑客的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆