如何摆脱这种黑客攻击

时间:2016-06-02 14:25:27

标签: dom typescript angular

我想修改类,以便它不使用ApplicationRef。换句话说,如何使用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,但它不起作用。

1 个答案:

答案 0 :(得分:0)

您可以使用ApplicationRef Brandon Roberts在https://github.com/angular/angular/issues/4112#issuecomment-139381970中演示的内容,以获取RouterCanActivate()的引用。

可能更好的是共享服务

@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);
  }
}