简体   繁体   中英

How to use window object in angular 7

I want to use scrollTo() function of window object. Directly by accessing window.scrollTo(0,0), i can achieve this functionality. When i googled about using window in angular, people are creating a provider like below one:

import {InjectionToken, FactoryProvider} from '@angular/core';

export const WINDOW = new InjectionToken<Window>('window');

const windowProvider: FactoryProvider = {
  provide: WINDOW,
  useFactory: () => window,
};

export const WINDOW_PROVIDERS = [windowProvider];

Inside service using like the below code:

import {Injectable, Inject} from '@angular/core';
import {WINDOW} from './window.provider';

@Injectable({
  providedIn: 'root',
})
export class WindowService {
  constructor(@Inject(WINDOW) public window: Window) {}
}

In module

    {provide: WINDOW_PROVIDERS, useValue: window},

Everything works with the above code, but while running test cases im getting the below error. Almost half of the application test cases are failing with below error

NullInjectorError: No provider for InjectionToken window!

Default Test case for window.service

import { TestBed } from '@angular/core/testing';

import { WindowService } from './window.service';

describe('WindowService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: WindowService = TestBed.get(WindowService);
    expect(service).toBeTruthy();
  });
});

How to fix this??

You need to set the following configureTestingModule :

TestBed.configureTestingModule({
    providers: [WINDOW_PROVIDERS, WindowService]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM