ngModel not updated with input value angular 2 test karma - javascript

I have a problem during my units test with angular 2. I just want to test an input to check if my model can't be more than 16 chars. (I have indeed use a maxlength in my html). So I enter a new value in my input and use dispatchEvent to set the input in the model but the model is nether update...
Here is my test :
/* tslint:disable:no-unused-variable */
import { EditRequestComponent } from './edit-request.component';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { __platform_browser_private__ as _ } from '#angular/platform-browser';
import { DebugElement } from '#angular/core';
import { MvpSelector } from './mvpSelector/mvpSelector.component';
import { MockBackend, MockConnection } from '#angular/http/testing';
import { FormsModule } from '#angular/forms';
import { ActivatedRoute } from '#angular/router';
import { Observable } from 'rxjs/Observable';
import { HttpModule, Http, BaseRequestOptions, Response } from '#angular/http';
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryWebApiService } from '../../services/in-memory.service';
import { MyDatePickerModule } from 'mydatepicker/dist/my-date-picker.module';
import { ReferentialService, RequestService, ConfigurationService } from '../../services';
import { MvpRequestClass } from '../../models';
//////// SPECS /////////////
describe('EditRequestComponent', function () {
let comp: EditRequestComponent;
let fixture: ComponentFixture<EditRequestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ReferentialService,
ConfigurationService,
RequestService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
return new Http(backend, options);
},
deps: [ MockBackend, BaseRequestOptions ]
},
{
provide: ActivatedRoute,
useValue: {
snapshot: {
params: {id: 1},
data: {request: new MvpRequestClass()}
}
}
}
],
declarations: [ MvpSelector, EditRequestComponent ],
imports: [ FormsModule, FormsModule, MyDatePickerModule,
HttpModule ]
}).compileComponents();
fixture = TestBed.createComponent(EditRequestComponent);
comp = fixture.componentInstance;
});
it('should create component', () => expect(comp).toBeDefined() );
it('should have a mvpRequestComponent', () =>
{
fixture.detectChanges();
expect(comp.mvpReq).toBeDefined();
});
it('should not have more than 16 char in moInCharge input', fakeAsync(() => {
comp.mvpReq.moInCharge = "oldValue";
fixture.detectChanges();
var field = fixture.debugElement.query(By.css('.input-moInCharge')).nativeElement;
field.value = "aaaaaaaaaaaaaaaaaaaaaa";
_.getDOM().dispatchEvent(field, _.getDOM().createEvent("input"));
tick();
console.log(field.value);
expect(comp.mvpReq.moInCharge.length).toBeLessThanOrEqual(16);
}));
});
Here are the Log print in my console:
LOG LOG: 'oldValue'
You can also see that I have a weird way to use dispatchEvent. That's because when I import and use it directly from '#angular/platform-browser/testing/browser_util' I have an error message :
Uncaught SyntaxError: Unexpected token import
at webpack:///~/#angular/platform-browser/testing/browser_util.js:8:0 <- karma.entry.js:49907
It seems that there was imports directly in the file browser_util.d.ts that our webpack doesn't appreciate. But the dispatchEvent function is sensibly used the same way. So I don't understand why the model doesn't update.
Here are few test that I made to make it work:
use async() function rather than fakeAsync
use the dispatchEvent function of MDN
use fixture.whenStable() with a then()
change the number of 'a' to check if the value doesn't update because
there are too many
a combination of all this points
And that's all. I must admit that I don't know how to proceed differently to make it work. If you can help me or you want more details, don't hesitate.
Thanks in advance.

Related

How to read subscribe in Angular Unit Test?

I am trying to write test cases of a component where at first I tried to check if a basic test case is working or not. There I encountered some errors related to Dependency Injection and solved those. Now the first issue that I am facing is mocking the API calls.
Below is my component code for which I am writing test cases:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HttpClientService } from '#service/http-client.service';
import { CustomErrorStateMatcher } from '#validator/error-state-matcher';
import { ToastrService } from 'ngx-toastr';
#Component({
selector: 'app-prep-card',
templateUrl: './prep-card.component.html',
styles: ['legend { width: fit-content !important; }']
})
export class PrepCardComponent implements OnInit {
constructor(private fb: FormBuilder, private _http: HttpClientService, private toastr: ToastrService) { }
foamTypeList: string[] = [];
colorList: string[] = [];
ngOnInit() { this.getFoam_ColorList() }
private getFoam_ColorList() {
this._http.getFoamType_ColorList('ABC').subscribe(response => {
this.foamTypeList = response.data.foamTypesAndColors.foamTypes;
this.colorList = response.data.foamTypesAndColors.colors;
});
}
}
At first, I tried to run a simple test case to check if it is working correctly or not. Below is the test case I wrote:
import { ComponentFixture, inject, TestBed } from "#angular/core/testing";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { RouterTestingModule } from '#angular/router/testing';
import { HttpClientService } from "#service/http-client.service";
import { ToastrService } from "ngx-toastr";
import { MaterialModule } from "src/app/material/material.module";
import { PrepCardComponent } from "./prep-card.component";
describe('PrepCardComponent', () => {
let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>,
_httpSpy: jasmine.SpyObj<HttpClientService>, _toastrSpy: jasmine.SpyObj<ToastrService>;
beforeEach(async () => {
const _httpSpyObj = jasmine.createSpyObj('HttpClientService', ['getFoamType_ColorList']),
_toastrSpyObj = jasmine.createSpyObj('ToastrService', ['success', 'error']);
await TestBed.configureTestingModule({
declarations: [PrepCardComponent],
imports: [
RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
],
providers: [
{ provide: HttpClientService, useValue: _httpSpyObj },
{ provide: ToastrService, useValue: _toastrSpyObj },
]
}).compileComponents();
fixture = TestBed.createComponent(PrepCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('test', () => expect('a').toBe('a'));
});
The above code snippet threw the following error:
TypeError: Cannot read properties of undefined (reading 'subscribe')
at PrepCardComponent.getFoam_ColorList (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:57:52)
at PrepCardComponent.setFormFieldValidator (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:65:10)
at PrepCardComponent.createForm (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:48:10)
at PrepCardComponent.ngOnInit (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:28:10)
at callHook (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2542:1)
at callHooks (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2511:1)
at executeInitAndCheckHooks (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2462:1)
at refreshView (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:9499:1)
at renderComponentOrTemplate (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:9598:1)
at tickRootContext (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:10829:1)
To solve this, I searched different questions here and saw common solution mentioned below to get an observable.
it('Call Service', inject([HttpClientService], (_http: HttpClientService) => {
spyOn(_http, 'getFoamType_ColorList').and.returnValue({subscribe: () => {}})
}));
Writing the above test case was throwing an error (mentioned below) in the subscribe position.
Type 'void' is not assignable to type 'Subscription'.ts(2322)
Service code
getFoamType_ColorList(cardType: string) {
return this.http.get<{ message: string, data: { foamTypesAndColors: { foamTypes: string[], colors: string[] } } }>
(`${this.URL}/validate/foam-type-and-color/${cardType}`);
}
Can anyone help me out with how I can solve this issue?
UPDATE
As per dmance's answer am not getting any error while writing the test case but the test cases are still failing giving the same error. For reference refer below the full error log:
I will suggest this:
import { of } from 'rxjs';
spyOn(httpclientservice, 'getFoamType_ColorList').and.returnValue(of(YOUR VALUE));
This is a more complete answer:
describe('PrepCardComponent', () => {
let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>;
let httpClientService: HttpClientService;
let toastService: ToastrService;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [PrepCardComponent],
imports: [
RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
]
}).compileComponents();
httpClientService = TestBed.inject(HttpClientService);
toastService= TestBed.inject(ToastrService);
fixture = TestBed.createComponent(PrepCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('test', () => {
spyOn(httpClientService, 'getFoamType_ColorList').then.returnValue(of(YOUR VALUE));
// MAKE YOUR TEST
});
});
Try this maybe
spyOn(_http,'getFoamType_ColorList').and.returnValue(Observable.of(Your_Value));

Why isn't http request being picked up in angular test

I have a simple service:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { ApiConfiguration } from '../../api/api-configuration';
import { BaseService } from '../../api/base-service';
import { Observable } from 'rxjs';
const TIMER = 120000;
#Injectable({
providedIn: 'root'
})
export class AppService extends BaseService {
constructor(
config: ApiConfiguration,
http?: HttpClient,
) {
super(config, http);
}
getContextualHelp(id, helpType): Observable<Object> {
return this.http.get(`${this.rootUrl}/api/v2/contextual-help`, {
params: { id, helpType }
});
}
}
I have tests that make sure the service returns some mocked data:
import { AppService } from '../app.service';
import { TestBed } from '#angular/core/testing';
import { HttpTestingController, HttpClientTestingModule } from '#angular/common/http/testing';
import { StoreModule } from '#ngrx/store';
import { ApiConfiguration } from '../../../api/api-configuration';
fdescribe('app.service', () => {
let service: AppService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
StoreModule.forRoot({}),
],
providers: [
AppService,
{
provide: ApiConfiguration, useValue: ''
},
]
});
service = TestBed.get(AppService);
httpMock = TestBed.get(HttpTestingController);
});
describe('getContextualHelp', () => {
it('should be created', () => {
expect(service).toBeTruthy();
});
it('calls the contextual help route with the expected params', () => {
const mockData = '<div></div>';
service.rootUrl = 'https://www.mock.com';
service.getContextualHelp('foo', 'bar').subscribe((html) => {
expect(html).toEqual('<div></div>');
});
const req = httpMock.expectOne('https://www.mock.com/api/v2/contextual-help');
req.flush(mockData);
});
});
});
It seems like I have everything hooked up correctly but when I run the test I get:
Error: Expected one matching request for criteria "Match URL: https://www.mock.com/api/v2/contextual-help", found none.
When I debug the test and go into the code context I see that http client is being called, and it's being called with the url I expect. So I guess somehow I misconfigured the test modules somehow? Does anyone see what I might have done wrong?
Note that expectOne() matches the url as well as the url params. Try to pass the complete url to the function, like:
const req = httpMock.expectOne('https://www.mock.com/api/v2/contextual-help?id=foo&helpType=bar');
Take a look at this question and the answer.

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 Loading the api configuration from the server side before the app bootstrap starts shows

I am using the angular 2 web app. In that, i am getting app configuration details from the api before the app bootsrap. For that i searched on the browser and find out these links
How to call an rest api while bootstrapping angular 2 app
https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9
And followed them. In the angular-cli and also on the browser console i didn't get any error. But my page comes empty with loading text, that was i displayed in the before loading angular.
Here is my code
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule, Http} from '#angular/http';
import { SocketIoModule, SocketIoConfig } from 'ng2-socket-io';
import { SharedModule } from './shared/shared.module';
import { TranslateModule, TranslateLoader} from '#ngx-translate/core';
import { TranslateHttpLoader} from '#ngx-translate/http-loader';
import { AppRoutingModule } from './app.route';
import { AppComponent } from './app.component';
import { ChatComponent } from './chat/chat.component';
import { ChatService } from './chat/chat.service';
import { AddressComponent } from './address/address.component';
import { HomeComponent } from './home/home.component';
import { SettingService } from './shared/service/api/SettingService';
import { FilterByPipe } from './filterPipe';
import { Ng2ScrollableModule } from 'ng2-scrollable';
import { AppConfig } from './app.config';
import {Injectable} from '#angular/core';
import {Observable} from 'rxjs/Rx';
const config: SocketIoConfig = { url: 'http://192.168.1.113:7002', options: {} };
export function HttpLoaderFactory(http: Http) {
return new TranslateHttpLoader(http, "http://192.168.1.114:7001/frontend-translation/", "");
}
export function SettingServiceFactory(setting: SettingService) {
return () => setting.load();
//return true;
}
#NgModule({
declarations: [
AppComponent,
ChatComponent,
AddressComponent,
HomeComponent,
FilterByPipe
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
Ng2ScrollableModule,
SocketIoModule.forRoot(config),
SharedModule,
TranslateModule.forRoot({
loader: {
provide : TranslateLoader,
useFactory: HttpLoaderFactory,
deps : [Http]
}
}),
],
providers: [
ChatService,
AppConfig,
SettingService,
{
provide : APP_INITIALIZER,
useFactory: SettingServiceFactory,
deps : [SettingService],
multi : true
}
/*SettingService,
{
provide : APP_INITIALIZER,
useFactory: (setting:SettingService) => () => setting.load(),
//deps : SettingService,
multi : true
}*/
],
bootstrap: [AppComponent]
})
export class AppModule { }
SettingService.ts
In this file, i am loading the api configuration from the server side
import {Injectable} from '#angular/core';
import {Http, Response} from '#angular/http';
import {Observable} from 'rxjs/Rx';
#Injectable()
export class SettingService {
public setting;
constructor(private http: Http) {}
/**
* Retrieves the setting details of the website
* #return {Object} language tranlsation
*/
public load()
{
return new Promise((resolve, reject) => {
this.http
.get('http://192.168.1.114:7001/settings')
.map( res => res.json() )
.catch((error: any):any => {
console.log('Configuration file "env.json" could not be read');
resolve(true);
return Observable.throw(error.json().error || 'Server error');
})
.subscribe( (envResponse) => {
this.setting = envResponse;
});
});
}
}
When i replace the load() api service within below code it works fine
public load() {
return {
"test": "works well"
}
}
But with api call, it doesn't.
What i found was, when i am returning the json object it works, but when i am making api call return the promise object it won't. I don't know how to solve this.
Thanks in advance.
My project was little bigger, so i can't put in plunker
Try to use promise object like this:
load(): Promise<Object> {
var promise = this.http.get('./app.json').map(res => res.json()).toPromise();
promise.then(res=> this.label= res);
return promise;
}

Categories