Getting error 'Expected undefined to be true' in Jasmine - javascript

Writing a test case for service function which should return true value.But i am getting error "Expected undefined to be true".below is the code for the same.
This is landingpage.serviice.spec.ts
import {Card} from "../../../shared/components/card/card.model";
import {} from 'jasmine';
import {LandingPageService} from "../../../features/admin/landing-page/landing-page.service";
import {ComponentFixture, TestBed} from "#angular/core/testing";
import {GBHttpClient, GBHttpClientCreator} from './../../../blocks/global/http-client';
import {HttpClient} from '#angular/common/http';
import {Principal,TokenService} from "../../../shared/auth";
import {Router} from '#angular/router';
import {MockRouter} from "../../../test-helpers/mock-route.service";
import {NgbModule} from "#ng-bootstrap/ng-bootstrap";
import {NgXTestModule} from "../../../test.module";
import {HttpClientTestingModule, HttpTestingController} from '#angular/common/http/testing';
import {MockBridgeService} from "../../../test-helpers/mock-bridge.service";
import {MockPrincipalService} from "../../../test-helpers/mock-principal.service";
import {TranslateService} from "#ngx-translate/core";
import {QuickTranslateService} from "../../../shared/services/quick-translate.service";
import {ParamsService} from './../../../shared/services/params.service';
import {SearchService} from "../../../features/search";
import {SpinnerService} from './../../../shared/spinner/spinner.service';
import {Observable,of} from 'rxjs';
describe('LandingPageService', () => {
// let result : boolean;
let landingPageService = {
checkLimitOrderFeatureEnabled: jasmine.createSpy(),
// checkItemCategoryLimit:jasmine.createSpy().and.returnValue(of(null))
}
let httpMock: HttpTestingController;
beforeEach(async() => {
const mockPrincipal = new MockPrincipalService();
const mockRouter = new MockRouter();
const mockBridgeService = new MockBridgeService();
const searchService = new SearchService(null, null);
await TestBed.configureTestingModule({
imports: [
NgXTestModule,
HttpClientTestingModule,
NgbModule.forRoot()
],
providers: [
{
provide: Principal,
useValue: mockPrincipal
},
{
provide: Router,
useValue: mockRouter
},
{
provide: "SearchService",
useValue: searchService
},
{
provide: "BridgeService",
useValue: mockBridgeService
},
LandingPageService,
TokenService,
QuickTranslateService,
TranslateService,
ParamsService,
SpinnerService,
{
provide: GBHttpClient,
useFactory: GBHttpClientCreator,
deps: [HttpClient]
}
]
})
landingPageService = TestBed.get(LandingPageService);
// result = false;
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
TestBed.resetTestingModule();
httpMock.verify();
});
it('should get Limit Order feature toggle value', () => {
spyOn(landingPageService,'checkLimitOrderFeatureEnabled').and.callThrough();
expect(landingPageService).toBeTruthy();
let result = landingPageService.checkLimitOrderFeatureEnabled();
expect(result).toBe(true);
});
});
This is landing-page.service.ts
checkLimitOrderFeatureEnabled() {
return this.principal.getUserContext().enableLimitOrder && this.principal.getUserContext().enableLimitOrderParameter;
}
For this function which is written in landingpage service i need to write test case.

Related

Unit test jasmine error in this.activatedRoute.queryParamMap.pipe

I have an Anuglar (version 8) application, that uses ngrx/store and RxJs for angular with this component:
export class CarComponent implements OnInit, OnDestroy {
// subscriptions
private unsubscribe$ = new Subject<void>();
constructor(
private activatedRoute: ActivatedRoute,
private readonly store: Store<any>,
private routingService: RoutingService,
private readonly carService: CarService) {}
ngOnInit(): void {
this.activatedRoute.queryParamMap.pipe(
takeUntil(this.unsubscribe$)).subscribe((paramMap: ParamMap) => {
this.store
.pipe(
select(selectDog, { dog: paramMap.get('carCode')})
)
.subscribe((car: Car) => {
this.setCar(Car);
}).unsubscribe();
});
}}
}
I have created an unit-test created with Karma and Jasmine:
import { ChangeDetectionStrategy } from '#angular/core';
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { ReactiveFormsModule } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { RouterTestingModule } from '#angular/router/testing';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { NgSelectModule } from '#ng-select/ng-select';
import { EffectsModule } from '#ngrx/effects';
import { Store, StoreModule } from '#ngrx/store';
import { Observable } from 'rxjs';
const scope = (): Scope => {
return {
carCode: '5288-5547-5247-4',
brandCar: '480',
};
};
describe('CarComponent ', () => {
let activatedRoute: ActivatedRoute;
let component: CarComponent;
let fixture: ComponentFixture<CarComponent>;
let store: Store<any>;
let routingService: RoutingService;
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
RouterTestingModule,
RouterTestingModule.withRoutes([]),
SharedModule,
StoreModule.forRoot({}),
StoreModule.forFeature(stayRestrictionsFeatureKey, stayRestrictionReducer),
StoreModule.forFeature(scopeFeatureKey, scopeReducer),
StoreModule.forFeature(inventoryFeatureKey, inventoryReducer),
StoreModule.forFeature(codeCarFeatureKey, codeCarReducer),
StoreModule.forFeature('scope', scopeReducer),
EffectsModule.forRoot([]),
NgbModule,
NgSelectModule,
NgOptionHighlightModule
],
providers: [{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParams: {
carCode: 'ss'
}
}
}
},
{
provide: Router,
useValue: {
routerState: {
snapshot : {
url : 'month/day/123'
}
}
}
}]
})
}));
beforeEach(() => {
activatedRoute = TestBed.get(ActivatedRoute.prototype.queryParamMap.pipe());
router = TestBed.get(Router);
routingService = TestBed.get(RoutingService);
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
store.dispatch(new LoadScopeSuccess(scope()));
fixture = TestBed.createComponent(CarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('init', () => {
spyOn(activatedRoute.queryParamMap, 'pipe').and.returnValue(new Observable());
component.ngOnInit();
const start = DateUtil.firstOfMonth();
const end = endDate(start, 3);
fixture.whenStable().then(_ => {
expect(component.searchCriteriaForm.get('carCode').value).toEqual('5288-5547-5247-4');
expect(component.searchCriteriaForm.get('brandCode').value).toEqual('480');
});
});
});
But when I launch the test I have this error:
1) init
CarComponent
TypeError: Cannot read property 'pipe' of undefined
at Object.get queryParamMap [as queryParamMap] (http://localhost:9876/_karma_webpack_/C:/Root/root-projects/[...]/client/node_modules/#angular/router/fesm2015/router.js:2747:1)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/monthly-view/monthly-view.component.spec.ts:90:59)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/C:/Root/root-projects/[...]/client/node_modules/zone.js/dist/zone-evergreen.js:359:1)
at ProxyZoneSpec.push.../../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/C:/Root/root-projects/[...]/client/node_modules/zone.js/dist/zone-testing.js:308:
1)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/C:/Root/root-projects/[...]/client/node_modules/zone.js/dist/zone-evergreen.js:358:1)
at Zone.run (http://localhost:9876/_karma_webpack_/C:/Root/root-projects/[...]/client/node_modules/zone.js/dist/zone-evergreen.js:124:1)
[...]
I have tried to mock the activate route but I have not found a solution. Have you a solution in order to bypass this problem? I thank you very much.
You have to mock activatedRoute.queryParamMap and unfortunately since it's not a method, you can't use pipe. I would do this:
import { ChangeDetectionStrategy } from '#angular/core';
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { ReactiveFormsModule } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { RouterTestingModule } from '#angular/router/testing';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { NgSelectModule } from '#ng-select/ng-select';
import { EffectsModule } from '#ngrx/effects';
import { Store, StoreModule } from '#ngrx/store';
import { Observable } from 'rxjs';
const scope = (): Scope => {
return {
carCode: '5288-5547-5247-4',
brandCar: '480',
};
};
describe('CarComponent ', () => {
let activatedRoute: ActivatedRoute;
let component: CarComponent;
let fixture: ComponentFixture<CarComponent>;
let store: Store<any>;
let routingService: RoutingService;
let router: Router;
// !! add this line
const mockQueryParamMap = new BehaviorSubject<any>({
get(value: string) => {
if (value === 'carCode') {
return '123'; // your mock for `carCode`
} else {
return '456';
}
}
});
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
RouterTestingModule,
RouterTestingModule.withRoutes([]),
SharedModule,
StoreModule.forRoot({}),
StoreModule.forFeature(stayRestrictionsFeatureKey, stayRestrictionReducer),
StoreModule.forFeature(scopeFeatureKey, scopeReducer),
StoreModule.forFeature(inventoryFeatureKey, inventoryReducer),
StoreModule.forFeature(codeCarFeatureKey, codeCarReducer),
StoreModule.forFeature('scope', scopeReducer),
EffectsModule.forRoot([]),
NgbModule,
NgSelectModule,
NgOptionHighlightModule
],
providers: [{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParams: {
carCode: 'ss'
}
}
}
},
{
provide: Router,
useValue: {
routerState: {
snapshot : {
url : 'month/day/123'
}
},
// !! add this line
queryParamMap: mockQueryParamMap,
},
}]
})
}));
it('init', () => {
// this is why we use BehaviorSubject so we have full control
// on what to push into the subscription
mockQueryParamMap.next({
get(value: string) => {
if (value === 'carCode') {
return '5288-5547-5247-4'; // your mock for `carCode`
} else {
return '456';
}
}
});
component.ngOnInit();
const start = DateUtil.firstOfMonth();
const end = endDate(start, 3);
fixture.whenStable().then(_ => {
expect(component.searchCriteriaForm.get('carCode').value).toEqual('5288-5547-5247-4');
expect(component.searchCriteriaForm.get('brandCode').value).toEqual('480');
});
});

Angular2 unit test. Check if a function calls router.navigate

I'm new to testing. Have a function that, when it's called, navigates to a new page. But the test is failing with an error:
Expected spy navigate to have been called with [ [
'./../admin/documents/12345' ] ] but it was never called.
public showProfile(id) {
this.router.navigate(['./../admin/documents/' + id]);
}
In my test file I have:
import {ComponentFixture, TestBed, fakeAsync, tick } from '#angular/core/testing';
import { AppComponent} from './app.component';
import {FormsModule} from "#angular/forms";
import {HttpClientTestingModule} from "#angular/common/http/testing";
import {Router} from "#angular/router";
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let mockRouter;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent],
imports: [FormsModule, HttpClientTestingModule],
providers: [
{ provide: Router, useValue: mockRouter }]
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
mockRouter = {
navigate: jasmine.createSpy('navigate')
};
});
describe('when showProfile() is called', () => {
it('navigates to a profile page',() => {
const id= 12345;
component.showProfile(id);
expect(mockRouter.navigate)
.toHaveBeenCalledWith(['./../admin/documents/' + id]);
});
});
});
You need to initialize the mockRouter before you use it in TestBed.configureTestingModule.
Also, expect(mockRouter.navigate).toHaveBeenCalledWith(['./../admin/documents/' + id]); won't work because ['a'] !== ['a']. As a workaround, you can do something like:
expect(mockRouter.navigate.calls.mostRecent().args[0][0])
.toEqual('./../admin/documents/' + id);
I've created a Stackblitz for your test.

importing the application constants error in angular jasmine test cases

When importing the component in component.spec the endponitConfig is thorwing the error as ReferenceError: endponitConfig is not defined
compoent.ts
import { Component, Type, OnInit, ViewEncapsulation, ViewChild } from '#angular/core';
import { Router } from '#angular/router';
import { Http, Response, Headers } from '#angular/http';
import { DriverService } from '../../services/driver.service';
import { endponitConfig } from '../../../../environments/endpoints';
#Component({
templateUrl: './drivers.list.component.html',
})
export class DriversListComponent {
//calling const form endpoint file
let driverEndpoint=endponitConfig.DRIVER_API_ENDPOINT;
//logic
}
Where endpoints.ts contains
export const endponitConfig: any = {
// Custom URL End Points
LOAD_API_ENDPOINT: '/dashboard/api/loadAppointments/',
LOAD_APPOINTMENT_API_ENDPOINT:'/dashboard/api/loadAppointmentType/',
DRIVER_API_ENDPOINT: '/dashboard/api/drivers/',
};
component.spec.ts
import { MockBackend } from '#angular/http/testing';
import { ModalDirective } from 'ngx-bootstrap';
import { DriverService } from '../../services/driver.service';
import { CommonModule, } from '#angular/common';
import { BaseRequestOptions, XHRBackend, Http, HttpModule } from '#angular/http';
import { SmartadminModule } from "../../../shared/smartadmin.module";
import { SmartadminDatatableModule } from "../../../shared/ui/datatable/smartadmin-datatable.module";
import { DataTableModule } from "angular2-datatable";
import { RouterTestingModule } from '#angular/router/testing';
import { Router, ActivatedRoute } from "#angular/router";
import { routing } from '../../drivers.routing';
import { ComponentLoaderFactory } from 'ngx-bootstrap';
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { DebugElement, NO_ERRORS_SCHEMA } from '#angular/core';
import { DriversListComponent } from './drivers.list.component';
import { MyDatePickerModule } from 'mydatepicker';
import { SelectModule } from 'angular2-select';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { CoreModule } from "../../../core/core.module";
import { BrowserModule } from '#angular/platform-browser';
import { endponitConfig } from '../../../../environments/endpoints';
let MockDriverArray = [
{
"id": 22,
"firstName": "Aaron",
"lastName": "Maisie",
"email": "aaron#test.net",
"phoneNumber": "2602185194",
}
];
describe('Driver list component', () => {
let driverListComponent: DriversListComponent;
let fixture: ComponentFixture<DriversListComponent>;
let router: Router;
let driverService, mockBackend;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [DriversListComponent],
imports: [SmartadminModule,
SmartadminDatatableModule,
MyDatePickerModule,
CommonModule,
SelectModule,
ReactiveFormsModule,
FormsModule,
// routing,
DataTableModule,
MyDatePickerModule,
BrowserModule,
// Error500Module,
CoreModule,
HttpModule,
RouterTestingModule.withRoutes([{
path: '', component: DriversListComponent
}])],
schemas: [NO_ERRORS_SCHEMA],
providers: [
DriverService,
MockBackend,
{ provide: XHRBackend, useClass: MockBackend }
]
})
.compileComponents();
router = TestBed.get(Router);
fixture = TestBed.createComponent(DriversListComponent);
driverListComponent = fixture.componentInstance;
driverService = TestBed.get(DriverService);
mockBackend = TestBed.get(MockBackend);
fixture.detectChanges();
}));
it('Driver Service should be defined', () => {
expect(driverService).toBeDefined();
});
it('Driver list page is loaded', () => {
expect(driverListComponent).toBeTruthy();
});
describe('Functional', () => {
it('should navigate to the update page for the driver.id of the driver passed in.', () => {
spyOn(router, 'navigate');
driverListComponent.goToUpdateDriverDetials(MockDriverArray[0]);
expect(router.navigate).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledTimes(1);
expect(router.navigate).toHaveBeenCalledWith(['/drivers/updateDriver', MockDriverArray[0].id]);
});
})
});
When executing the spec file it throwing an error ReferenceError: endponitConfig is not defined
ReferenceError: endponitConfig is not defined
at Plugin.init (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:145039:22)
at new Plugin (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:144781:14)
at HTMLElement.<anonymous> (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:146128:48)
at Function.each (http://localhost:9876/base/node_modules/jquery/dist/jquery.min.js?1055018c28ab41087ef9ccefe411606893dabea2:2:2715)
at r.fn.init.each (http://localhost:9876/base/node_modules/jquery/dist/jquery.min.js?1055018c28ab41087ef9ccefe411606893dabea2:2:1003)
at r.fn.init.Array.concat.$.fn.(anonymous function) [as jarvisWidgets] (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:146123:21)
at WidgetsGridComponent.Array.concat.WidgetsGridComponent.ngAfterViewInit (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:128191:51)
at callProviderLifecycles (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:11542:18)
at callElementProvidersLifecycles (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:11517:13)
at callLifecycleHooksChildrenFirst (http://localhost:9876/base/src/test.ts?32930bead8e68a3814014a7f2e341a3b291fe038:11501:17)
Please help out...
New to unit test cases in angular

How do I test a JSONP HTTP request in Angular?

I'm using the HttpClientModule and HttpClientJsonpModule to make a JSONP HTTP request in a service.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule, HttpClientJsonpModule } from '#angular/common/http';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
HttpClientJsonpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This service uses the jsonp method from the HttpClient class to get a JSONP response from the specified URL. I think that this response is intercepted by JsonpInterceptor and sent to the JsonpClientBackend where the request is handled.
example.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class ExampleService {
url = "https://archive.org/index.php?output=json&callback=callback";
constructor(private http: HttpClient) { }
getData() {
return this.http.jsonp(this.url, 'callback');
}
}
Using the HttpClientTestingModule, I inject the HttpTestingController so I can mock and flush my JSONP HTTP request.
example.service.spec.ts
import { TestBed, inject } from '#angular/core/testing';
import {
HttpClientTestingModule,
HttpTestingController
} from '#angular/common/http/testing';
import { ExampleService } from './example.service';
describe('ExampleService', () => {
let service: ExampleService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ExampleService]
});
service = TestBed.get(ExampleService);
httpMock = TestBed.get(HttpTestingController);
});
describe('#getData', () => {
it('should return an Observable<any>', () => {
const dummyData = { id: 1 };
service.getData().subscribe(data => {
expect(data).toEqual(dummyData);
});
const req = httpMock.expectOne(service.url); // Error
expect(req.request.method).toBe('JSONP');
req.flush(dummyData);
});
});
});
In the end, I get the error
Error: Expected one matching request for criteria "Match URL: https://archive.org/index.php?output=json&callback=callback", found none.
If I change the request method to GET, this test works as expected.
From what I can tell, the HttpClientTestingModule uses the HttpClientTestingBackend but there is no JsonpClientTestingBackend or corresponding interceptor.
How do I test a JSONP HTTP request in Angular?
According to an Angular developer this is a bug. Here's a workaround for now.
example.service.spec.ts
import { TestBed, inject } from '#angular/core/testing';
// Import the HttpClientJsonpModule, HttpBackend, and JsonpClientBackend
import { HttpClientJsonpModule, HttpBackend, JsonpClientBackend } from '#angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { ExampleService } from './example.service';
describe('ExampleService', () => {
let service: ExampleService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
// Use the HttpBackend instead of the JsonpClientBackend
providers: [ExampleService, { provide: JsonpClientBackend, useExisting: HttpBackend }]
});
service = TestBed.get(ExampleService);
httpMock = TestBed.get(HttpTestingController);
});
describe('#getData', () => {
it('should return an Observable<any>', () => {
const dummyData = { id: 1 };
service.getData().subscribe(data => {
expect(data).toEqual(dummyData);
});
// Pass a function to the expectOne method
const req = httpMock.expectOne(request => request.url === service.url);
expect(req.request.method).toBe('JSONP');
req.flush(dummyData);
});
});
});

angular2 translate ionic 2 No provider for Http! (MyApp -> TranslateService -> Http)

I am using ionic2/angular2 and ng2-translate. I get an error of "No provider for Http! (MyApp -> TranslateService -> Http)". I am not using typescript. I believe that this code is in typescript form. can someone help me convert it to javascript. Because i am using javascript for my ionic2 project. here is the code from the documentation of ng2-translate. I am just new to ionic2 and angular2.
import {provide} from '#angular/core';
import {TranslateService, TranslateLoader, TranslateStaticLoader} from 'ng2-translate/ng2-translate';
#App({
templateUrl: '....',
config: {},
providers: [
provide(TranslateLoader, {
useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
deps: [Http]
}),
TranslateService
]
})
here is my app.js
import {App, IonicApp, Platform, Storage, SqlStorage} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {MainPage} from './pages/main/main';
import {TabsPage} from './pages/jeepney/tabs/tabs';
import {LandingPage} from './pages/landingpage/landingpage';
// import {JeepneyRoutesPage} from './pages/jeepney/jeep-routes/jeep-routes';
// import {ListPage} from './pages/list/list';
import {DataService} from './services/data';
import {ConnectivityService} from './providers/connectivity-service/connectivity-service';
import {GoogleMapsService} from './providers/google-maps-service/google-maps-service';
import {LoadingModal} from './components/loading-modal/loading-modal';
import {provide} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {TranslateService, TranslateLoader, TranslateStaticLoader} from 'ng2-translate/ng2-translate';
#App({
templateUrl: 'build/app.html',
providers: [DataService,ConnectivityService,
HTTP_PROVIDERS,
provide(TranslateLoader, {
useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
deps: [Http]
}),
TranslateService],
directives: [LoadingModal],
config: {
iconMode: 'md',
modalEnter: 'modal-slide-in',
modalLeave: 'modal-slide-out',
pageTransition: 'ios',
tabSubPages: false,
backButtonIcon: 'ios-arrow-back',
tabbarPlacement: 'top',
backButtonText: ''
// menuType: 'reveal'
} // http://ionicframework.com/docs/v2/api/config/Config/
})
class MyApp {
static get parameters() {
return [[IonicApp], [Platform],[TranslateService]];
}
constructor(app, platform,translate) {
this.translate=translate;
// set up our app
this.app = app;
this.platform = platform;
this.initializeApp();
// make HelloIonicPage the root (or first) page
this.rootPage = LandingPage;
// this.initializeTranslateServiceConfig();
var userLang = navigator.language.split('-')[0]; // use navigator lang if available
userLang = /(fr|en)/gi.test(userLang) ? userLang : 'en';
// this language will be used as a fallback when a translation isn't found in the current language
this.translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them
this.translate.use(userLang);
}
initializeTranslateServiceConfig() {
var prefix = 'assets/i18n/';
var suffix = '.json';
this.translate.useStaticFilesLoader(prefix, suffix);
var userLang = navigator.language.split('-')[0];
userLang = /(de|en|hr)/gi.test(userLang) ? userLang : 'en';
this.translate.setDefaultLang('en');
this.translate.use(userLang);
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
// this.storage = new Storage(SqlStorage);
// this.storage.query('CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)').then((data) => {
// console.log("TABLE CREATED -> " + JSON.stringify(data.res));
// }, (error) => {
// console.log("ERROR -> " + JSON.stringify(error.err));
// });
});
}
}
You need to provide HTTP_PROVIDERS:
import {HTTP_PROVIDERS, Http} from '#angular/http';
#App({
templateUrl: '....',
config: {},
providers: [
HTTP_PROVIDERS,
provide(TranslateLoader, {
useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
deps: [Http]
}),
TranslateService
]
})
this is how it worked out for me.
check out the app.module.ts file
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TranslateModule, TranslateStaticLoader, TranslateLoader } from 'ng2-translate/ng2-translate';
import { Http } from '#angular/http'
export function createTranslateLoader(http: Http) {
return new TranslateStaticLoader(http, 'assets/i18n', '.json');
}
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp),
TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
})
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
you can find a complete repo here:
https://github.com/philipphalder/ionic2-rc3-NG2-Translate

Categories