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.
Related
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.
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..!
My node definitions looks like this:
class Store {}
let store = new Store()
let nodeDefs = nodeDefinitions(
(globalId) => {
let type = fromGlobalId(globalId).type
let id = fromGlobalId(globalId).id
if (type === 'Store') {
return store
}
if (type === 'Video') {
return docClient.query(
Object.assign(
{},
{TableName: videosTable},
{KeyConditionExpression: 'id = :id'},
{ExpressionAttributeValues: { ':id': id }}
)
).promise().then(dataToConnection)
}
return null
},
(obj) => {
if (obj instanceof Store) {
return storeType
}
if (obj instanceof Video) {
return videoType
}
return null
}
)
The problem is that video node is always null, even when actual video is being returned from the database, because for it to not be null I need to look it up based on id or somehow fetch it from database.
This is the video node I am referring to:
video: {
type: videoType,
args: Object.assign(
{},
connectionArgs,
{id: {type: GraphQLString}}
),
resolve: (_, args) => {
return docClient.query(
Object.assign(
{},
{TableName: pokemonTable},
{KeyConditionExpression: 'id = :id'},
{ExpressionAttributeValues: { ':id': args.id }},
paginationToParams(args)
)
).promise().then(dataToConnection)
}
},
and
const videoType = new GraphQLObjectType({
name: 'Video',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLID),
resolve: (obj) => obj.id
},
name: { type: GraphQLString },
url: { type: GraphQLString }
}),
interfaces: [nodeDefs.nodeInterface]
})
const allVideosConnection = connectionDefinitions({
name: 'Video',
nodeType: videoType
})
I tried doing database query directly inside node definitions, but that didn't work.
dataToConnection just converts the output of dynamoDB:
video DATA!! { Items:
[ { id: 'f4623d92-3b48-4e1a-bfcc-01ff3c8cf754',
url: 'http://www.pokkentournament.com/assets/img/characters/char-detail/detail-pikachuLibre.png',
name: 'YAHOO' } ],
Count: 1,
ScannedCount: 1 }
into something that graphql relay understands:
video dataToConnection!! { edges:
[ { cursor: 'ZHluYW1vZGJjb25uZWN0aW9uOmY0NjIzZDkyLTNiNDgtNGUxYS1iZmNjLTAxZmYzYzhjZjc1NA==',
node: [Object] } ],
pageInfo:
{ startCursor: 'ZHluYW1vZGJjb25uZWN0aW9uOmY0NjIzZDkyLTNiNDgtNGUxYS1iZmNjLTAxZmYzYzhjZjc1NA==',
endCursor: 'ZHluYW1vZGJjb25uZWN0aW9uOmY0NjIzZDkyLTNiNDgtNGUxYS1iZmNjLTAxZmYzYzhjZjc1NA==',
hasPreviousPage: false,
hasNextPage: false } }
and the function itself can be found here: https://github.com/dowjones/graphql-dynamodb-connections/pull/3/files
It could be the problem.
Also, asking/querying for id makes the whole video object null:
But omitting id from the query returns something, whether querying with relay id:
or database id
and querying for all of the videos works:
The interesting part is that I get exactly same problem even if I delete the video part from node definitions:
let nodeDefs = nodeDefinitions(
(globalId) => {
let type = fromGlobalId(globalId).type
let id = fromGlobalId(globalId).id
if (type === 'Store') {
return store
}
return null
},
(obj) => {
if (obj instanceof Store) {
return storeType
}
return null
}
)
Any ideas?
UPDATE:
I did some digging and found that interfaces in fact is undefined
const storeType = new GraphQLObjectType({
name: 'Store',
fields: () => ({
id: globalIdField('Store'),
allVideosConnection: {
type: allVideosConnection.connectionType,
args: Object.assign(
{},
connectionArgs
),
resolve: (_, args) => {
return docClient.scan(
Object.assign(
{},
{TableName: pokemonTable},
paginationToParams(args)
)
).promise().then(dataToConnection)
}
},
video: {
type: videoType,
args: Object.assign(
{},
connectionArgs,
{id: {type: GraphQLString}}
),
resolve: (_, args) => {
return docClient.query(
Object.assign(
{},
{TableName: pokemonTable},
{KeyConditionExpression: 'id = :id'},
{ExpressionAttributeValues: { ':id': args.id }},
paginationToParams(args)
)
).promise().then(dataToConnection)
}
}
}),
interfaces: [nodeDefs.nodeInterface]
})
console.dir(storeType.interfaces, { depth: null })
prints undefined
Why? I clearly define them at the top!
Also, I can do that:
But this doesn't work:
This is what is being returned in video: {} resolve:
{ edges:
[ { cursor: 'ZHluYW1vZGJjb25uZWN0aW9uOmY0NjIzZDkyLTNiNDgtNGUxYS1iZmNjLTAxZmYzYzhjZjc1NA==',
node:
{ id: 'f4623d92-3b48-4e1a-bfcc-01ff3c8cf754',
url: 'http://www.pokkentournament.com/assets/img/characters/char-detail/detail-pikachuLibre.png',
name: 'YAHOO' } } ],
pageInfo:
{ startCursor: 'ZHluYW1vZGJjb25uZWN0aW9uOmY0NjIzZDkyLTNiNDgtNGUxYS1iZmNjLTAxZmYzYzhjZjc1NA==',
endCursor: 'ZHluYW1vZGJjb25uZWN0aW9uOmY0NjIzZDkyLTNiNDgtNGUxYS1iZmNjLTAxZmYzYzhjZjc1NA==',
hasPreviousPage: false,
hasNextPage: false } }
Somehow that's okay for allVideosConnection, but not okay (ends up null) for video
Do I need to convert ids of nodes to global IDs? using toGlobalId ? Just for video ?
Because another thing I noticed is that if I
console.log('fromGlobalId', fromGlobalId(globalId))
inside my node definitions, this query:
{
node(id: "f4623d92-3b48-4e1a-bfcc-01ff3c8cf754") {
id
...F1
}
}
fragment F1 on Video {
url
name
}
becomes this:
fromGlobalId { type: '', id: '\u000e6]_v{vxsn\u001eU/\u001b}G>SW_]O\u001c>x' }
However, if I do
I get
globalId U3RvcmU6
fromGlobalId { type: 'Store', id: '' }
So to make node definitions work, all I had to do was this:
class Video {}
let video = new Video()
return Object.assign(video, data.Items[0])
i.e. create class with the same name as type name
and then Object.assign to it
Just doing this, doesn't work:
return {Video: data.Items[0]}
I also need to create IDs in the database like that: Video:f4623d92-3b48-4e1a-bfcc-01ff3c8cf754, where I am essentially putting type and randomly generated unique id together separated by a colon (:) and then encode it with toGlobalId function of graphql-relay-js library (so I end up with VmlkZW86ZjQ2MjNkOTItM2I0OC00ZTFhLWJmY2MtMDFmZjNjOGNmNzU0Og==), so then I can decode it with fromGlobalId so that node definitions can retrieve both type and id({ type: 'Video', id: 'f4623d92-3b48-4e1a-bfcc-01ff3c8cf754:' }), after which I still need to add fromGlobalId(globalId).id.replace(/\:$/, '')) to remove the trailing colon (:).
`
Also, interfaces are not meant to be accessible, they are just for configuration.
I am relatively new to ember and am just taking a look at it for the first time, I am using ember-cli-mirage as a mock server and am having some issues.
In my models/groups.js I have
export default DS.Model.extend({
name: DS.attr('string'),
serverType: DS.attr('string', {defaultValue: 'Web Server'}),
protectionMode: DS.attr('string', {defaultValue: 'High'}),
protectionLevel: DS.attr('string', {defaultValue: '=)'}),
bps: DS.attr('number'),
pps: DS.attr('number'),
protectedHosts: DS.attr('string', {defaultValue: '1.0.0.0'}),
lastModified: DS.attr('number', {defaultValue: 1}),
complete: DS.attr('string')
});
I originally did not have default values in anywhere but once I added them content showed up in my templates for serverType, protectionMode, protectionLevel but not lastModified or protectedHosts
My mirage/config.js
export default function() {
this.get('/groups', function(db, request) {
console.log(db.groups)
return {
data: db.groups.map(attrs => (
{type: 'groups', id: attrs.id, attributes: attrs}
))
};
});
this.post('/groups', function(db, request) {
let attrs = JSON.parse(request.requestBody);
let group = db.groups.insert(attrs);
return {
data: {
type: 'groups',
id: group.id,
attributes: group
}
};
});
this.patch('/groups/:id', function(db, request) {
let attrs = JSON.parse(request.requestBody);
let group = db.groups.update(attrs.data.id, attrs.data.attributes);
return {
data: {
type: 'groups',
id: group.id,
attributes: group
}
};
});
this.del('/groups/:id');
}
The console logging I am doing in the /groups get is showing all of the correct data from my mirage/factories
mirage/factories/groups.js
import Mirage, {faker} from 'ember-cli-mirage';
export default Mirage.Factory.extend({
name(i) { return `Protection Group ${i + 1}`; },
serverType(i) { return `Custom Server Type ${i + 1}`;},
protectionMode: 'High',
protectionLevel: '=)',
lastModified(i) { return `${i+1} Weeks`; },
bps(i) { return parseInt(Math.floor((Math.random() * i) + 100 * i)) },
pps(i) { return parseInt(Math.floor((Math.random() * 100) + i)) },
protectedHosts(i) { return `10.1.2.1${i+1}`; },
complete: false
});
Anyone have any idea why some data is showing up as undefined and some is not and why some default values are working but some are not?
For protectedHosts and lastModified you spelled defaultValue incorrectly. You have defualtValue (the u and a are reversed).
breeze is supposed to wrap properties with observable and observableArrays by default, right? Why is it not doing it in this case?
var apiService = new breeze.DataService({
serviceName: 'api',
hasServerMetadata: false
});
var store = new breeze.MetadataStore({
namingConvention: breeze.NamingConvention.camelCase
});
var movieType = new breeze.EntityType({
shortName: 'Movie',
dataProperties: [
new breeze.DataProperty({
name: "id",
dataType: breeze.DataType.ID,
isNullable: false,
isPartOfKey: true
}),
new breeze.DataProperty({
name: "title",
dataType: breeze.DataType.String,
isNullable: false
})
]
});
store.addEntityType(movieType);
function Movie() {
var self = this;
self.isBeingEdited = false;
}
store.registerEntityTypeCtor('Movie', Movie);
var manager = new breeze.EntityManager({
dataService: apiService,
metadataStore: store
});
var favoriteMovie = movieType.createEntity({
id: 123,
title: "5th Element",
stars: ['Bruce Willis', 'Milla Yovovich']
});
manager.addEntity(favoriteMovie);
alert(favoriteMovie.title()); //errors favoriteMovie.title is not a function
The above code is fine. The problem was that I included breeze.js before knockout.js The order of inclusion is important.