/**
  * Helper methods to add ComponentClass(like modal backdrop) with options
  * of type ComponentOptionsClass to element next to application root
  * or next to provided instance of view container
  * @param ComponentClass - @Component class
  * @param ComponentOptionsClass - options class
  * @param options - instance of options
  * @param contextInjector - injector to resolve root view container (any injector except root injector will fit)
  * @returns {ComponentRef<T>} - returns ComponentRef<T>
  */
 public appendNextToRoot<T>(ComponentClass:Type<T>,
                            ComponentOptionsClass:any,
                            options:any,
                            contextInjector:Injector):ComponentRef<T> {
   let location = this.getRootViewContainerRef(contextInjector);
   let providers = ReflectiveInjector.resolve([
     {provide: ComponentOptionsClass, useValue: options}
   ]);
   return this.appendNextToLocation(ComponentClass, location, providers);
 }
Example #2
0
  beforeEach(function() {
    routeSet$ = new Subject<Match>();
    spyOn(router, 'replace');
    spyOn(observer, 'next');
    const injector = ReflectiveInjector.resolveAndCreate([
      provide(Router, { useValue: router })
    ]);

    redirect = injector.resolveAndInstantiate(RedirectHook);
  });
Example #3
0
  beforeEach(function() {
    routerInstruction$ = new Subject<Match>();
    const injector = ReflectiveInjector.resolveAndCreate([
      PARAMS_PROVIDERS,
      provide(RouterInstruction, { useValue: routerInstruction$ })
    ]);

    routeParams$ = injector.get(RouteParams);
    queryParams$ = injector.get(QueryParams);
  });
Example #4
0
    beforeEach(function () {
        const injector = ReflectiveInjector.resolveAndCreate([
            ShopEffects,
            MOCK_EFFECTS_PROVIDERS,
            // Mock out other dependencies (like Http) here
        ]);

        shop = injector.get(ShopEffects);
        updates$ = injector.get(MockStateUpdates);
    });
Example #5
0
 useInjectors(): void {
     let injector: any = ReflectiveInjector.resolveAndCreate([
         ViewPortService,
         provide('OtherSizeService', {useFactory: (viewport: any) => {
             return viewport.determineService();
         }, deps: [ViewPortService]})
     ]);
     let sizeService: any = injector.get('OtherSizeService');
     sizeService.run();
 }
Example #6
0
 it('should infer type', () => {
   // #docregion InjectionToken
   const BASE_URL = new InjectionToken<string>('BaseUrl');
   const injector =
       ReflectiveInjector.resolveAndCreate([{provide: BASE_URL, useValue: 'http://localhost'}]);
   const url = injector.get(BASE_URL);
   // here `url` is inferred to be `string` because `BASE_URL` is `InjectionToken<string>`.
   expect(url).toBe('http://localhost');
   // #enddocregion
 });
Example #7
0
 beforeEach(() => {
   var injector = ReflectiveInjector.resolveAndCreate(
       [{provide: ResponseOptions, useClass: BaseResponseOptions}, MockBackend]);
   backend = injector.get(MockBackend);
   var base = new BaseRequestOptions();
   sampleRequest1 = new Request(base.merge(new RequestOptions({url: 'https://google.com'})));
   sampleResponse1 = new Response(new ResponseOptions({body: 'response1'}));
   sampleRequest2 = new Request(base.merge(new RequestOptions({url: 'https://google.com'})));
   sampleResponse2 = new Response(new ResponseOptions({body: 'response2'}));
 });
 beforeEach(() => {
   let injector = ReflectiveInjector.resolveAndCreate([
     ROUTER_FAKE_PROVIDERS,
     // Angulartics2 relies on router for virtual page view tracking
     Angulartics2, Angulartics2Segment, AnalyticsService
   ]);
   analyticsService = injector.get(AnalyticsService);
   analyticsService.devMode(false);
   segment = injector.get(Angulartics2Segment);
 });
  beforeEach(() => {
    onerrorSpy = jasmine.createSpy('onerror');
    superHandler = spyOn(ErrorHandler.prototype, 'handleError');

    const injector = ReflectiveInjector.resolveAndCreate([
      { provide: ErrorHandler, useClass: ReportingErrorHandler },
      { provide: WindowToken, useFactory: () => ({ onerror: onerrorSpy }) }
    ]);
    handler = injector.get(ErrorHandler);
  });
function createInjector(initialUrl: string) {
  return ReflectiveInjector.resolveAndCreate([
      DocumentService,
      { provide: LocationService, useFactory: () => new MockLocationService(initialUrl) },
      { provide: ConnectionBackend, useClass: MockBackend },
      { provide: RequestOptions, useClass: BaseRequestOptions },
      { provide: Logger, useClass: MockLogger },
      Http,
  ]);
}
Example #11
0
 beforeEach(() => {
   injector = ReflectiveInjector.resolveAndCreate([
     HTTP_PROVIDERS,
     // Provide a mocked (fake) backend for Http
     { provide: XHRBackend, useClass: MockBackend }
   ]);
   backend = injector.get(XHRBackend);
   // sets the connection when someone tries to access the backend with an xhr request
   backend.connections.subscribe((c: MockConnection) => connection = c);
 });
Example #12
0
            .then(cmpFactory => {
                const vcr = this._viewContainer,
                      bindings = this._compileConfig.bindings,
                      ctxInjector = vcr.parentInjector;

                const childInjector = Array.isArray(bindings) && bindings.length > 0 ?
                    ReflectiveInjector.fromResolvedProviders(bindings, ctxInjector) : ctxInjector;
                return this.dialog.contentRef =
                    vcr.createComponent(cmpFactory, vcr.length, childInjector);
            });
 beforeEach(() => {
   injector = ReflectiveInjector.resolveAndCreate([
       NavigationService,
       { provide: LocationService, useFactory: () => new MockLocationService('a') },
       { provide: ConnectionBackend, useClass: MockBackend },
       { provide: RequestOptions, useClass: BaseRequestOptions },
       Http,
       Logger
   ]);
 });
Example #14
0
export function bootstrapModuleFactory<M>(moduleFactory: AppModuleFactory<M>): AppModuleRef<M> {
  let platformInjector = browserPlatform().injector;
  // Note: We need to create the NgZone _before_ we instantiate the module,
  // as instantiating the module creates some providers eagerly.
  // So we create a mini parent injector that just contains the new NgZone and
  // pass that as parent to the AppModuleFactory.
  let ngZone = new NgZone({enableLongStackTrace: isDevMode()});
  let ngZoneInjector =
      ReflectiveInjector.resolveAndCreate([{provide: NgZone, useValue: ngZone}], platformInjector);
  return ngZone.run(() => { return moduleFactory.create(ngZoneInjector); });
}
Example #15
0
  it('should alias devtools to the store backend', () => {
    const injector = ReflectiveInjector.resolveAndCreate([
      provideStore(counter),
      instrumentStore()
    ]);

    const devtools = injector.get(StoreDevtools);
    const backend = injector.get(StoreBackend);

    expect(devtools).toBe(backend);
  });
Example #16
0
  function createStore(reducer, monitorReducer = T => T){
    const injector = ReflectiveInjector.resolveAndCreate([
      provideStore(reducer),
      instrumentStore(monitorReducer)
    ]);

    const store = injector.get(Store);
    const devtools = injector.get(StoreDevtools);

    return { store, devtools };
  }
Example #17
0
export function bootstrap(
    appComponentType: Type,
    customProviders?: Array<any /*Type | Provider | any[]*/>): Promise<ComponentRef<any>> {
  reflector.reflectionCapabilities = new ReflectionCapabilities();
  let providers = [
    BROWSER_APP_PROVIDERS, BROWSER_APP_COMPILER_PROVIDERS,
    isPresent(customProviders) ? customProviders : []
  ];
  var appInjector = ReflectiveInjector.resolveAndCreate(providers, browserPlatform().injector);
  return coreLoadAndBootstrap(appComponentType, appInjector);
}
Example #18
0
export function bootstrapWorkerApp(
    appComponentType: Type,
    customProviders?: Array<any /*Type | Provider | any[]*/>): Promise<ComponentRef<any>> {
  var appInjector = ReflectiveInjector.resolveAndCreate(
      [
        WORKER_APP_APPLICATION_PROVIDERS, WORKER_APP_COMPILER_PROVIDERS,
        isPresent(customProviders) ? customProviders : []
      ],
      workerAppPlatform().injector);
  return coreLoadAndBootstrap(appComponentType, appInjector);
}
 return inject(tokens, (tcb, router, location, backend, userService, loginService) => {
   // TODO it's not a good idea, but I have no other way.
   // It must be resolved in https://github.com/angular/angular/issues/4112
   appInjector(ReflectiveInjector.resolveAndCreate([
     provide(UserService, {useValue: userService}),
     provide(LoginService, {useValue: loginService}),
     provide(Router, {useValue: router}),
   ]));
   const ctx = new TestContext({tcb, router, location, backend});
   fn(ctx);
 });
Example #20
0
    it('should alias devtools unlifted state to Store\'s state', () => {
      const injector = ReflectiveInjector.resolveAndCreate([
        provideStore(counter),
        instrumentStore()
      ]);

      const devtools: StoreDevtools = injector.get(StoreDevtools);
      const state = injector.get(State);

      expect(devtools.state).toBe(state);
    });
      .then(factory => {
        // Create Injector for Component
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);

        // Create Component with factory and injector. 0 = index which determines where in the
        // container the component will be rendered. 0 means it will be rendered starting at the
        // beginning
        const componentRef = this.vcRef.createComponent(factory, 0, injector, []);

        // Define any parameters you want to pass to the newly generated component
        componentRef.instance.item = this.item;
      });
Example #22
0
  protected createContainer<T>(
    dialogRef: DialogRef<any>,
    ContainerComponent: Class<T>,
    content: string | TemplateRef<any> | Type<any>,
    bindings?: ResolvedReflectiveProvider[]): ComponentRef<T> {

    const b = ReflectiveInjector.resolve([{provide: DialogRef, useValue: dialogRef}])
      .concat(bindings || []);

    let nodes: any[] = dialogRef.overlayRef.instance.getProjectables(content, b);
    return dialogRef.overlayRef.instance.addComponent<T>(ContainerComponent, b, nodes);
  }
Example #23
0
    beforeEach(() => {
        const injector = ReflectiveInjector.resolveAndCreate([
            { provide: CoreWebService, useValue: coreWebServiceMock },
            { provide: DotcmsConfig, useValue: dotcmsConfig },
            { provide: DotEventsSocketURL, useValue: url },
            StringUtils,
            LoggerService,
            DotEventsSocket
        ]);

        dotEventsSocket = injector.get(DotEventsSocket);
    });
 beforeEach(() => {
     injector = ReflectiveInjector.resolveAndCreate([
         AlfrescoContentService,
         AlfrescoAuthenticationService,
         AlfrescoSettingsService
     ]);
     spyOn(localStorage, 'getItem').and.callFake(function (key) {
         return 'myToken';
     });
     service = injector.get(AlfrescoContentService);
     authService = injector.get(AlfrescoAuthenticationService);
 });
  /**
   * Creates an instance of a Component and attaches it to the View Container found at the
   * `location` specified as {@link ViewContainerRef}.
   *
   * You can optionally provide `providers` to configure the {@link Injector} provisioned for this
   * Component Instance.
   *
   * Returns {@link ComponentRef} representing the newly created Component.
   * @param ComponentClass - @Component class
   * @param location - reference to the location
   * @param providers - optional array of providers
   * @returns {ComponentRef<T>} - returns ComponentRef<T>
   */
  public appendNextToLocation<T>(ComponentClass:Type<T>,
                                 location:ViewContainerRef,
                                 providers?:ResolvedReflectiveProvider[]):ComponentRef<T> {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ComponentClass);
    let parentInjector = location.parentInjector;
    let childInjector: Injector = parentInjector;
    if (providers && providers.length > 0) {
      childInjector = ReflectiveInjector.fromResolvedProviders(providers, parentInjector);
    }

    return location.createComponent(componentFactory, location.length, childInjector);
  }
Example #26
0
export function useInjector() {
  var injector: ReflectiveInjector;
  // #enddocregion injector
  /*
  // #docregion injector-no-new
  // Cannot instantiate an ReflectiveInjector like this!
  var injector = new ReflectiveInjector([Car, Engine, Tires]);
  // #enddocregion injector-no-new
  */
  // #docregion injector, injector-create-and-call
  injector = ReflectiveInjector.resolveAndCreate([Car, Engine, Tires]);
  // #docregion injector-call
  var car = injector.get(Car);
  // #enddocregion injector-call, injector-create-and-call
  car.description = 'Injector';

  injector = ReflectiveInjector.resolveAndCreate([Logger]);
  var logger = injector.get(Logger);
  logger.log('Injector car.drive() said: '+car.drive());
  return car;
}
Example #27
0
    it('should combine reducers automatically if a key/value map is provided', () => {
      const reducers = { test: function(){} };
      spyOn(reducers, 'test');
      const action = { type: 'Test Action' };
      const reducer = ReflectiveInjector.resolveAndCreate([ provideStore(reducers) ]).get(INITIAL_REDUCER);

      expect(reducer).toBeDefined();
      expect(typeof reducer === 'function').toBe(true);

      reducer(undefined, action);

      expect(reducers.test).toHaveBeenCalledWith(undefined, action);
    });
        it("requires a Translator", () => {
            let injector = ReflectiveInjector.resolveAndCreate([ TranslatePipe ]);

            let action = () => {
                try {
                    injector.get(TranslatePipe);
                } catch (e) {
                    expect(e.message).toContain("No provider for Translator!");
                    throw e;
                }
            };
            expect(action).toThrow();
        });
Example #29
0
export function createInjector({
  ngModule,
  providers,
}: ModuleWithProviders): ReflectiveInjector {
  const injector = ReflectiveInjector.resolveAndCreate([
    ...(providers || []),
    ngModule,
  ]);

  injector.get(ngModule);

  return injector;
}
Example #30
0
    it('should use asap scheduler by default', function () {
      const rootInjector = ReflectiveInjector.resolveAndCreate([ SagaTester ]);
      let tester: SagaTester = rootInjector.get(SagaTester);

      const saga = createSaga<number>(() => saga$ => saga$
        .filter(whenAction(ADD))
        .map(() => ({ type: SUBTRACT })));

      tester.run(saga);

      tester.sendAction({ type: ADD })
      expect(tester.last).toEqual({ type: SUBTRACT })
    });