How to display the observable data using the service in angular - javascript

home.component.ts
<h1>{{ (reportsToday$ | async)}}</h1>
<div echarts [options]="alertsDaily$ | async">
<div echarts [options]="alertsToday$ | async">
<div [onDisplay]="alertsDaily$ | async">
report.component.ts
constructor(private report: ReportService) {}
getReports() {
this.report.getStatusReport();
}
report.service.ts
displayAlert$ = new BehaviorSubject(undefined);
reportsToday$ = new BehaviorSubject(undefined);
alertsToday$ = new BehaviorSubject(undefined);
alertsDaily$ = new BehaviorSubject(undefined);
constructor() {}
getStatusReport() {
loading = {
today: false,
daily: false
};
this.loading.today = true;
this.loading.daily = true;
const severities = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];
const reportModules = [
{ url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } },
{
url: 'application1',
params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() }
},
{
url: 'application2',
params: {
to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
}
},
{
url: 'application3',
params: {
to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
}
}
];
const promises = applicationModule.map(
target =>
new Promise(resolve => {
this.notificationService
.getSummary(target.url, target.params)
.pipe(take(1))
.subscribe(
(result: Response) =>
resolve({ target, result });
},
(err: Error) => {
// return reject(err);
}
);
})
);
Promise.all(promises).then(results => {
const options = this.preConfig;
const week = this.getWeek();
results.forEach((res: any) => {
....
if (res.target.url !== '') {
if (res.target.url === 'application1') {
....
this.loading.today = false;
this.alertsToday$.next(options.today);
}else {
if (res.target.url === 'application2') {
...
...
this.loading.daily = false;
this.alertsDaily$.next(options.daily);
} else {
....
....
this.loading.daily = false;
this.alertsDaily$.next(options.daily);
}
}
}else {
this.reportsToday$.next(res.result[0]);
}
}
});
}
The problem here is it doesn't display the observable data. When I run the application there's no error, but it doesn't display the data of displayAlert$, reportsToday$, alertsToday$ and alertsDaily$.
I used service it because, I will use it from the other components.
How to get the observable from service and display it on home component?

In component you can't see the variable directly from service. It should be from component itself.
Also you need to subscribe the values you are firing with .next(). Unless you subscribe them , the value won't be set.

I think new BehaviorSubject(undefined); is causing the problem.
Can you initialize like new BehaviorSubject([]); or if it is string then new BehaviorSubject(''); and if number then new BehaviorSubject(0);
I am assuming that you have correctly called service from components.

Related

How to fix "Type 'Promise<{}>' is missing the following properties from type 'Observable<any>'" in angular

Here's the code:
const reportModules = [
{ url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } },
{
url: 'application1',
params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() }
},
{
url: 'application2',
params: {
to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
}
},
{
url: 'application3',
params: {
to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
}
}
];
const promises = reportModules.map(
target =>
new Promise(resolve => {
this.notificationService
.getSummary(target.url, target.params)
.pipe(take(1))
.subscribe(
(result: Response) => {
resolve({ target, result });
},
(err: Error) => {
// return reject(err);
}
);
})
);
const observables: Observable<any>[] = promises;
merge(...observables).subscribe((results) => { ... }
how to fix the error let observables: Observable<any>[]
'observables' is declared but its value is never read.ts(6133)
Type 'Promise<{}>[]' is not assignable to type 'Observable<any>[]'.
Type 'Promise<{}>' is missing the following properties from type 'Observable<any>': _isScalar, source, operator, lift, and 6 more.ts(2322).
What I'm trying to do here to load the first call then second until the end of the promise.
for example it will call the first which is the application1 after that the application2, it should call it one by one.
The error is in the last two lines of your code. You're assigning a list of promises to a list of observables. They're not the same type of object.
The simplest fix would be to just stick to Promises and use Promise.all() instead of merge().

How to update the echarts in angular

here's the code:
HTML
<div echarts [options]="alertsToday$ | async" (chartInit)="onChartInit(todayCharts.line, $event)"
[theme]="(darkMode$ | async) ? 'dark' : 'default'" style="max-height: 200px;"></div>
TS
todayOptions = chartOptions.today;
todayCharts: any = {
line: { options: _.cloneDeep(this.todayOptions) }
};
constructor(private report: ReportService){}
onChartInit(chart: object, instance: any) {
chart['instance'] = instance;
this.todayCharts.line['instance'].setOption(this.todayCharts.line.options);
}
getReports() {
this.report.getStatusReports();
this.report.alertsToday$.subscribe((data) => {
this.alertsToday$.next(data);
if (this.todayCharts.line['instance']) {
this.todayCharts.line['instance'].setOption(data);
}
}
SERVICE.TS
getStatusReports() {
const severities = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];
const reportModules = [
{ url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } },
{
url: 'application-and-severity',
params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() }
},
{
url: 'application-and-severity-and-date',
params: {
to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
}
},
{
url: 'application-and-status',
params: {
to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
}
}
];
const promises = reportModules.map(
target =>
new Promise(resolve => {
this.notificationService
.getSummary(target.url, target.params)
.pipe(take(1))
.subscribe(
(result: Response) => {
// console.log(target, result);
resolve({ target, result });
},
(err: Error) => {
// return reject(err);
}
);
})
);
Promise.all(promises).then(results => {
const options = chartOptions;
options.default.today.series[0].itemStyle.normal.label.formatter = function (params: any) { return params.value + '%\n'; };
const week = this.getWeek();
// console.log(options.default);
results.forEach((res: any) => {
if (res.target.url !== '') {
if (res.target.url === 'application-and-severity') {
const todaySummary = { total: 0, data: [] as any };
const groups = _.groupBy(res.result, (data: any) => data.severity);
severities.forEach(severity => {
const total = groups[severity]
? groups[severity].reduce((prev, curr) => ({ total: prev.total + curr.total }))
: {
total: 0
};
todaySummary.data.push({
name: severity,
value: total.total
});
todaySummary.total += total.total;
});
options.default.today.title.text = todaySummary.total;
options.default.today.series[0].data = todaySummary.data;
// this.loading.today = false;
return this.alertsToday$.next(options.default.today);
}
}
});
});
}
What I'm trying to do here is to update the charts of alertsToday. but when I try to use the setOption it doesn't work and I used the onChartInit().
first the data is displaying, but when there's a new update it doesn't reload/refresh or update the chart.
how to update the echarts? cause it load the first data then when I update the data it doesn't update the echarts it still the same.
I have chart.component.html and chart.component.ts and report.service also the acknowledge.component.ts

Angular jqxSchedular source localData Can't bind from remote

I am trying to use jqxSchedular for my web app.
Schedular couldn't bind from remote data.
Here is my Angular component:
export class CourseScheduleComponent implements OnInit {
appointmentDataFields: any =
{
from: "start",
to: "end",
description: "description",
subject: "subject",
resourceId: "calendar"
};
source = {
dataType: "array",
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'subject', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date' },
{ name: 'end', type: 'date' }
],
localData: []
}
resources: any =
{
colorScheme: "scheme04",
dataField: "calendar",
source: new jqx.dataAdapter(this.source)
};
dataAdapter: any;
date: any = new jqx.date();
views: string[] | any[] =
[
'dayView',
'weekView',
'monthView',
'agendaView'
];
constructor(private repository: RepositoryService,private router: Router,
private activeRoute: ActivatedRoute ) { }
ngOnInit() {
this.getCourseSchedules().subscribe(res=>{
this.source.localData = res as CourseSchedule[];
},err=>{
console.log(err);
});
this.dataAdapter = new jqx.dataAdapter(this.source)
}
getCourseSchedules()
{
var courseId : string = this.activeRoute.snapshot.params['id'];
var apiUrl = `/api/course/schedule?courseId=${courseId}`;
return this.repository.getData(apiUrl).pipe(
map(data => {
let schedules = data as CourseSchedule[];
let newSchedules:CourseSchedule[] = [];
schedules.forEach((schedule) => {
const {start,end,...other} = schedule;
newSchedules.push(<CourseSchedule>{
start: new Date(start),
end: new Date(end),
...other
})
});
return newSchedules;
})
);
}
}
When I debug the ngOnInit there is no problem with setting localData. But when I consolled log source,it shows localdata is null.
I couldnt find for remote databinding example for Angular jqxSchedular.
So ,basicly it works with local data but at remote it doesnt work.
Please help about this.
You have to add them from the jqx component using addAppointment method as below:
getCourseSchedules()
{
let self = this;
var courseId : string = this.activeRoute.snapshot.params['id'];
var apiUrl = `/api/course/schedule?courseId=${courseId}`;
return this.repository.getData(apiUrl).pipe(
map(data => {
let schedules = data as CourseSchedule[];
let newSchedules:CourseSchedule[] = [];
schedules.forEach((schedule) => {
const {start,end,...other} = schedule;
var appointment = {
start: new Date(start),
end: new Date(end),
..other
};
self.myScheduler.addAppointment(appointment);
});
})
);
}
Please refer to the API for more details.

Jasmine test with selecting items from list

I have an angular application and I need to do some unit testing on some methods with Jasmine. IN this case I do a unit test on a select list. So that the select list will not be empty.
The method looks like this:
createStatusOptions(listValueoptions: OptionModel[], resources: any): OptionModel[] {
const processStatusOptions = listValueoptions.map(listValueOption => {
listValueOption.value = `${caseStatusEnum.inProgress}_${listValueOption.value}`;
listValueOption.selected = true;
return listValueOption;
});
const caseStatusEnumKeys = Object.keys(caseStatusEnum).filter(key => !isNaN(Number(key)));
const enumOptions = this.optionService.createOptions(
new ConfigOptionModel({ source: caseStatusEnumKeys, resources, resourcesModel: enumResourcesModel, isCustomEnum: true, }));
return [
this.getEnumOption(enumOptions, caseStatusEnum.submitted, true),
...processStatusOptions,
this.getEnumOption(enumOptions, caseStatusEnum.closed),
];
}
private getEnumOption(options: OptionModel[], enumType, isSelected = false): OptionModel {
const option = options.filter(enumOption => enumOption.value === `${enumType}`)[0];
option.selected = isSelected;
return option;
}
And I have the unit test like this:
it('should create status options when there ar list value options are provided', () => {
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:max-line-length
const result = service.createStatusOptions(optionService.options, [[103], [104], [105] ]);
console.log(result);
expect(result.length).toBe(2);
expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
});
But I get an error like this:
Services: CaseService > should create status options when there ar list value options are provided
TypeError: Cannot set property 'selected' of undefined
at <Jasmine>
at CaseService.getEnumOption (http://localhost:9878/src/app/case/src/services/case.service.ts?:130:9)
at CaseService.getEnumOption [as createStatusOptions] (http://localhost:9878/src/app/case/src/services/case.service.ts?:109:22)
at UserContext.<anonymous> (http://localhost:9878/src/app/case/src/services/case.service.spec.ts?:149:32)
at ZoneDelegate.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:388:1)
at ProxyZoneSpec.push.../../node_modules/zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/proxy.js?:128:1)
at ZoneDelegate.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:387:1)
at Zone.../../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:138:1)
at runInTestZone (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/jasmine-patch.js?:145:1)
at UserContext.<anonymous> (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/jasmine-patch.js?:160:1)
at <Jasmine>
So my question is: How to solve this?
Thank you
if I do this:
console.log(optionService.options);
I get this output:
Array(3)
0: {value: "103", selected: true}
1: {value: "104"}
2: {value: "105", selected: false}
length: 3
__proto__: Array(0)
this is the file:
import { fakeAsync, tick } from '#angular/core/testing';
import { FormServiceMock, MultiFileUploadServiceMock } from 'afw/forms/testing';
import { AfwHttp } from 'afw/generic-services';
import { AfwHttpMock, OptionServiceMock } from 'afw/generic-services/testing';
import { OptionModel, SearchResultModel } from 'afw/models';
import { FeedbackStoreServiceMock } from 'afw/store-services/testing';
import { RouterMock } from 'afw/testing';
import { PagingDataModel, TableSortDataModel } from 'afw/ui-components';
import { caseOwnerEnum, caseStatusEnum, caseTypeEnum, MultiFileUploadResourcesModel } from 'lr/models';
import { Observable, observable } from 'rxjs';
import { CaseTypeInfoModel } from 'support-shared/base/models';
import { CaseTypeInfoStoreServiceMock } from 'support-shared/base/services/case-type-info-store.service.mock';
import { CaseFormComponent } from '../case-base/src/case-form/case-form.component';
import { CaseBaseModel, CaseReferenceModel } from '../models';
import { CaseService } from './case.service';
let service: CaseService;
let afwHttpMock: AfwHttpMock;
// tslint:disable-next-line:prefer-const
let formServiceMock: FormServiceMock;
let multiFileUploadService: MultiFileUploadServiceMock;
let router: RouterMock;
let feedbackStoreService: FeedbackStoreServiceMock;
let optionService: OptionServiceMock;
let caseTypeInfoStoreService: CaseTypeInfoStoreServiceMock;
// tslint:disable-next-line:prefer-const
let component: CaseFormComponent;
fdescribe('Services: CaseService', () => {
beforeEach(() => {
afwHttpMock = new AfwHttpMock();
multiFileUploadService = new MultiFileUploadServiceMock();
router = new RouterMock();
feedbackStoreService = new FeedbackStoreServiceMock();
optionService = new OptionServiceMock();
caseTypeInfoStoreService = new CaseTypeInfoStoreServiceMock();
service = new CaseService(afwHttpMock as any, multiFileUploadService as any, router as any,
feedbackStoreService as any, optionService as any, caseTypeInfoStoreService as any);
});
it('should create an instance', () => {
expect(service).toBeTruthy();
});
it('should get case reference details', () => {
afwHttpMock.setupOnlyResponse({ type: caseTypeEnum.revisionRequest, details: { bsn: 'bsnLabel' } }, 200);
const d = service.getCaseReferenceDetails('spinnerMessage', { reference: '112314121', type: caseTypeEnum.revisionRequest });
d.subscribe(r => {
expect(r.details.length === 1);
expect(r.details[0].key).toBe('bsn');
expect(r.details[0].value).toBe('bsnLabel');
expect((r.details[0] as any).resourceKey).toBe('bsn');
});
afwHttpMock.returnSuccessResponse();
});
// tslint:disable-next-line:no-identical-functions
it('should get case reference details with full response', () => {
afwHttpMock.setupOnlyResponse({ body: { type: caseTypeEnum.revisionRequest, details: [{ key: 'hoi' }] } }, 200);
const d = service.getCaseReferenceDetailsFullResponse('spinnerMessage', { reference: '100001075', type: caseTypeEnum.revisionRequest });
// tslint:disable-next-line:no-commented-code
// tslint:disable-next-line:no-identical-functions
/* let result;
d.subscribe(r => {
result = r;
}); */
d.subscribe(r => {
expect(r.ok === true);
expect(r.body.details[0].key).toBe('hoi');
});
afwHttpMock.returnSuccessResponse();
// expect(result.ok === true);
// expect(result.)
});
// tslint:disable-next-line:no-commented-code
it('shoud get case type info configuration that is used on various views when snapshot exists', () => {
let result99: Observable<CaseTypeInfoModel[]>;
result99 = service.getCaseTypeInfo('spinner') as Observable<CaseTypeInfoModel[]>;
const response = [{ mock: 'mock' } as any];
service['caseTypeInfoSnapshot'] = response;
service.getCaseTypeInfo('spinner').subscribe(i => {
expect(i).toEqual(response);
});
});
// tslint:disable-next-line:no-identical-functions
it('shoud get case type info configuration that is used on various views when snapshot doesnt exists', () => {
let result99: Observable<CaseTypeInfoModel[]>;
const spy = spyOn(caseTypeInfoStoreService, 'addCaseTypeInfoToStore');
result99 = service.getCaseTypeInfo('spinner') as Observable<CaseTypeInfoModel[]>;
const response = [{ mock: 'mock' } as any];
service['caseTypeInfoSnapshot'] = response;
// caseTypeInfoStoreService..subscribe((result) => { expect(result).toBe(false); });
result99.subscribe((result) => {
expect(response).toEqual(response);
});
afwHttpMock.setupOnlyResponse(result99, 200);
afwHttpMock.returnSuccessResponse();
});
it('should create status options when no list value options are provided', () => {
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:no-commented-code
// const spy = spyOn(service, 'createStatusOptions');
const result = service.createStatusOptions([], {});
expect(result.length).toBe(2);
expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
// tslint:disable-next-line:no-commented-code
// const response = [{ mock: 'mock' } as any];
// expect(spy).toBe(result);
});
it('should create status options when there ar list value options are provided', () => {
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:max-line-length
const result = service.createStatusOptions(optionService.options, 103);
console.log(optionService.options);
expect(result.length).toBe(2);
expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
});
it('should get case reference without details', () => {
afwHttpMock.setupOnlyResponse({}, 200);
const spy = spyOn(afwHttpMock, 'post').and.callThrough();
const model = new CaseReferenceModel({ reference: '112314121', type: caseTypeEnum.revisionRequest });
const d = service.getCaseReferenceDetails('spinnerMessage', model);
d.subscribe(r => {
expect(r).toBeDefined();
});
expect(spy).toHaveBeenCalledWith('api/support/cases/get-reference-details', model, 'spinnerMessage');
afwHttpMock.returnSuccessResponse();
});
it('should add case reference without details', () => {
afwHttpMock.setupOnlyResponse({}, 200);
const spy = spyOn(afwHttpMock, 'post').and.callThrough();
const model = new CaseReferenceModel({ reference: '112314121', type: caseTypeEnum.revisionRequest });
const d = service.addCase('spinnerMessage', model as any);
d.subscribe(r => {
expect(r).toBeDefined();
});
expect(spy).toHaveBeenCalledWith('api/support/cases', model, 'spinnerMessage');
afwHttpMock.returnSuccessResponse();
});
it('should search for cases', () => {
const formModel: any = { makeQueryString: () => 'name=test' };
const pagingModel = new PagingDataModel({ currentPage: 10, itemsPerPage: 20 });
const sortModel = new TableSortDataModel({ columnName: 'kol', isDescending: false });
const spy = spyOn(afwHttpMock, 'get').and.callThrough();
const mockData = [
new CaseBaseModel({
id: 100000001,
type: caseTypeEnum.revisionRequest,
status: caseStatusEnum.inProgress,
substatus: 5266,
verdict: null,
owner: caseOwnerEnum.caseManager,
dateSubmitted: '02-02-2009',
dateClosed: '',
reference: 'aaa',
}),
];
const setupResponse = new SearchResultModel<CaseBaseModel>();
setupResponse.result = mockData;
setupResponse.totalResultCount = 27;
afwHttpMock.setupOnlyResponse(setupResponse, 200);
let response: SearchResultModel<CaseBaseModel>;
service.search(formModel, sortModel, pagingModel, 'spinnerText').subscribe(result => {
response = result;
});
afwHttpMock.returnOnlyResponse();
expect(spy).toHaveBeenCalledWith('api/support/cases?name=test&columnName=kol&isDescending=false&currentPage=10&itemsPerPage=20',
'spinnerText');
expect(response).toEqual(setupResponse);
expect(response.result[0].getResourceForStatus).toBeDefined();
});
it('should save documents', fakeAsync(() => {
const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
const spyRouter = spyOn(router, 'navigate').and.callThrough();
const spyFeedback = spyOn(feedbackStoreService, 'addSuccessMessageOnMainPortal');
service.saveDocuments(1, [{} as any], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
expect(spy).toHaveBeenCalledWith('api/support/cases/1/documents', [{}],
MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
);
tick();
expect(spyRouter).toHaveBeenCalledWith(['../']);
expect(spyFeedback).toHaveBeenCalled();
}));
it('should not save documents if there are no documents in array', fakeAsync(() => {
const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
const spyRouter = spyOn(router, 'navigate').and.callThrough();
const spyFeedback = spyOn(feedbackStoreService, 'addSuccessMessageOnMainPortal');
service.saveDocuments(1, [], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
expect(spy).not.toHaveBeenCalled();
tick();
expect(spyRouter).toHaveBeenCalledWith(['../']);
expect(spyFeedback).toHaveBeenCalled();
}));
it('should save documents and report errors', fakeAsync(() => {
multiFileUploadService.setResponse([{}, { error: {} }]);
spyOn(multiFileUploadService, 'makeWarningMessageForUnsyncedFiles').and.returnValue('mock');
const spyRouter = spyOn(router, 'navigate').and.callThrough();
const spyFeedback = spyOn(feedbackStoreService, 'addWarningMessageOnMainPortal');
const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
service.saveDocuments(1, [{} as any], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
expect(spy).toHaveBeenCalledWith('api/support/cases/1/documents', [{}],
MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
);
tick();
expect(spyRouter).toHaveBeenCalledWith(['../']);
expect(spyFeedback).toHaveBeenCalled();
}));
it('should get case by id', () => {
const id = 66208014;
const setupResponse = new CaseBaseModel({
id,
dateSubmitted: '',
owner: caseOwnerEnum.caseManager,
reference: 'ksjhkjshdf',
status: caseStatusEnum.submitted,
type: caseTypeEnum.revisionRequest,
});
afwHttpMock.setupOnlyResponse(setupResponse, 200);
service.getCase(id, 'spinner').subscribe(r => {
expect(r).toEqual(setupResponse);
});
afwHttpMock.returnSuccessResponse();
});
it('edit the case with model', () => {
const spy = spyOn(service, 'editCase').and.callThrough();
const caseUpdate = new CaseBaseModel({
id: 100001075,
dateSubmitted: '',
owner: caseOwnerEnum.caseManager,
reference: 'ksjhkjshdf',
status: caseStatusEnum.submitted,
type: caseTypeEnum.revisionRequest,
});
service.editCase('spinner', caseUpdate);
expect(spy).toHaveBeenCalledWith('spinner', caseUpdate);
expect(caseUpdate.id).toEqual(100001075);
});
});
Based on what you showed so far, my guess is that the options parameter passed to getEnumOption() is undefined, which is causing the error you see. A quick console.log(options) within getEnumOption() would verify this.
If your code is working fine otherwise, but only failing in the test then I would make a second guess that you haven't properly mocked/spiedOn this.optionService.createOptions() since it sets up the options parameter that is potentially undefined. That would have been done earlier in the .spec file - if you post the whole file then that would help others who read your question to determine if this is the case.
Update with Stackblitz
I put all your code into a Stackblitz to test it. There was a lot of code I didn't have access to that I just guessed at the functionality of. However, I did discover a few things.
First, when you are testing you appear to be using the same variable both for the mock of the return expected by this.optionService.createOptions() as well as in the call to service.createStatusOptions() - which is likely not what you want to do.
Here is the code snippet I am talking about:
optionService.options = [
{
value: caseStatusEnum.submitted.toString(),
},
{
value: caseStatusEnum.inProgress.toString(),
},
{
value: caseStatusEnum.closed.toString(),
},
] as OptionModel[];
// tslint:disable-next-line:max-line-length
const result = service.createStatusOptions(optionService.options, [[103], [104], [105] ]);
When I called it this way in the Stackblitz I ran into a mutability issue - you are changing the data within the members of the objects inside the array, which will change it whereever that variable is accessed. To overcome this in the Stackblitz I made two copies of the data, one to use in the mock returnValue and another completely separate array of objects for the call to service.createStatusOptions(). Also, I am not familiar with the way you are mocking your service call, so I replaced it with a simple Jasmine spy in the Stackblitz.
Feel free to have a look at what I produced. Perhaps it will be helpful.

Data Binding with Smart table from json file

i want to bind the json file to a smart table. How to use the loop function for the iteration.. please help
It only shows the design of smart table.
didn't binding the data from json
this is the json file
[
{
"year": 2013,
"id": "",
"doctor": "Dr. Smith",
"illness": "Flu",
"apptdate": "3/12/2013",
"details":"Patient had flu for 5 days. No medicines prescribed"
}
]
i used to retrieve data using
#Injectable()
export class SmartTablesService {
constructor(private http: Http) {
}
smartTableData = [];
loadData() {
console.log('loadData');
this.http.get('http://192.168.0.100:8000/medical')
.subscribe((data) => {
setTimeout(() => {
var contactData = [];
$.each(data.json(), function (key, value) {
var tempData = value.source;
contactData.push(tempData);
});
this.smartTableData = contactData;
}, 1000);
});
}
getData(): Promise<any> {
console.log("Promise");
this.loadData();
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(this.smartTableData);
resolve(this.smartTableData);
}, 3000);
});
}
}
constructor(private http: Http) { }
getComments() {
return this.http.get('http://192.168.0.100:8000/article' )
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error));
}
}*/
this is the component part
#Component({
selector: 'new',
template: '<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>'
})
export class NewComponent {
query: string = '';
settings = {
noDataMessage: 'Loading...',
columns: {
year: {
title: 'YEAR',
type: 'string'
},
id: {
title: 'ID',
type: 'string'
},
doctor: {
title: 'DOCTOR',
type: 'string'
},
illness: {
title: 'ILLNESS',
type: 'string'
},
apptdate: {
title: 'APPTDATE',
type: 'string'
},
details: {
title: 'DETAILS',
type: 'string'
}
}
};
// data
source: LocalDataSource = new LocalDataSource();
constructor(protected service: SmartTablesService){
this.service.getData().then((data) => {
this.source.load(data);
});
}
}
please anyone anyone know how to bind it ..help
simply change the subscribe part in the service page to
var tempData = value;
so .subscriber looks like
.subscribe((data) => {
setTimeout(() => {
var contactData = [];
$.each(data.json(), function (key, value) {
var tempData = value; contactData.push(tempData);
});
this.smartTableData = contactData;
}, 1000);
});
}
it works..!

Categories