load data to grid in angular 6 using http get - jqgrid

Im trying to load the following sample data to jqgrid(free) using http.get in angular 6.
[{"maker":"Toyota", "model":"Celica"},{ "maker": "Chrysler", "model":"Mondeo"}]
Model Class
export class Model{
maker : string
model : string
}
Component:
...
#Component({...})
export class SampleComponent implements OnInit {
private _sampleService;
columnModel : any[];
models : Model[];
constructor(_sampleService : SampleService) {
this._sampleService = _sampleService;
}
ngOnInit() {
this.columnModel = [{ name: "maker" },{ name: "model" }]
this.models = this._sampleService.getModelList().subscribe(models => this.models = models);
}
ngAfterViewInit() {
(<any>jQuery("#grid")).jqGrid({
colModel: this.columnModel,
data: this.models
});
}
}
Service:
....
#Injectable()
export class SampleService{
constructor(private http : HttpClient){}
getModelList():Observable<Model[]>{
return this.http.get<Model[]>
("http://localhost:8090/myapp/getModel");
}
}
If I do the following, I can see the data in the console.
this.http.get("http://localhost:8090/ducksoup/getModel")
.subscribe(data => {console.log(data)})
But,it is not rendering in the grid. Any help?

You can write your jqxGrid binding code inside of OnInit method, right after you fetch your records and it will show your data on datagrid

Related

Auto-updating model list with custom sorting

I am trying to apply custom sorting to the models; however, using the sort computed property is sorting the models on the initial load of the page but it is not auto-updating the page when more models are entered into the store.
Ember-Source: 4.7.0
Ember-Data: 4.7.3
Ember-CLI: 4.6.0
Ember-CLI-Typescript: 2.4.0
app/models/item.ts:
import Model, { attr } from '#ember-data/model';
export default class Item extends Model {
#attr('string')
declare name: string;
}
// DO NOT DELETE: this is how TypeScript knows how to look up your models.
declare module 'ember-data/types/registries/model' {
export default interface ModelRegistry {
'item': Item;
}
}
app/routes/index.ts:
import Route from '#ember/routing/route';
import { service } from '#ember/service';
import type Store from '#ember-data/store';
export default class Index extends Route {
#service
declare store : Store;
async model(){
return this.store.peekAll('item');
}
}
app/controllers/index.ts:
import Controller from '#ember/controller';
import { sort } from '#ember/object/computed';
import Item from 'sorting-test/models/item';
const sortNumeric = (a: Item, b: Item) => parseInt(a.id, 10) - parseInt(b.id, 10);
export default class Index extends Controller {
#sort("model", sortNumeric)
declare sortedModels: Item[]
}
// DO NOT DELETE: this is how TypeScript knows how to look up your controllers.
declare module '#ember/controller' {
interface Registry {
'index': Index;
}
}
app/templates/index.hbs:
{{#model.length}}:{{this.sortedModels.length}}
tests/acceptance/index-test.ts:
import { module, test } from 'qunit';
import { visit, settled } from '#ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import type Store from '#ember-data/store';
module('Acceptance | index', function (hooks) {
setupApplicationTest(hooks);
test('visiting /', async function (assert) {
const store = this.owner.lookup('service:store') as Store;
await visit('/');
assert.equal(this.element.textContent, '0:0');
store.createRecord('item', {id: '10', name: 'A'});
store.createRecord('item', {id: '2', name: 'B'});
await settled();
assert.equal(this.element.textContent, '2:2');
});
});
Passes the first assertion but the second assertion fails with:
actual: > 2:0
expected: > 2:2
I have tried changing the line #sort("model", sortNumeric) to use different combinations of model.[], model.#each, model.#each.id but none of them seem to have any effect.
How do get the template to auto-update with custom sorting? (and is this a reoccurrence of https://github.com/emberjs/ember.js/issues/19101)?
Change the controller to use a native getter rather than the sort computed property:
import Controller from '#ember/controller';
import Item from 'sorting-test/models/item';
const sortNumeric = (a: Item, b: Item) => parseInt(a.id, 10) - parseInt(b.id, 10);
export default class Index extends Controller {
// Declare the model otherwise typescript raises errors.
declare model: Item[];
get sortedModels(){
// Copy the array otherwise sort will try to re-order it in place and fail.
return this.model.slice().sort(sortNumeric);
}
}
// DO NOT DELETE: this is how TypeScript knows how to look up your controllers.
declare module '#ember/controller' {
interface Registry {
'index': Index;
}
}

Loopback4 hasMany not return the link array

I just try to use the hasMany relationship according to the loopback4 documentation .but it's not working as expected.
My Bus Model =>
export class Bus extends Entity {
#property({
type: 'number',
id: true,
generated: true,
})
id?: number;
#hasMany(() => BusStation, {keyTo: 'busId'})
stations?: BusStation[];
constructor(data?: Partial<Bus>) {
super(data);
}
}
export interface BusRelations {
// describe navigational properties here
}
export type BusWithRelations = Bus & BusRelations ;
Bus Station Model =>
export class BusStation extends Entity {
#property({
type: 'number',
id: true,
generated: true,
})
id?: number;
#property({
type: 'number',
})
busId: number;
#property({
type: 'string',
required: true,
})
name: string;
constructor(data?: Partial<BusStation>) {
super(data);
}
}
export interface BusStationRelations {
// describe navigational properties here
}
export type BusStationWithRelations = BusStation & BusStationRelations;
Bus Repository =>
export class BusRepository extends DefaultCrudRepository<
Bus,
typeof Bus.prototype.id,
BusRelations
> {
public stations: HasManyRepositoryFactory<
BusStation,
typeof Bus.prototype.id
>;
constructor(
#inject('datasources') dataSource: MyDataSource,
#repository.getter('BusStationRepository')
busStationRepositoryGetter: Getter<BusStationRepository>,
) {
super(Bus, dataSource);
this.stations = this.createHasManyRepositoryFactoryFor(
'stations',
busStationnRepositoryGetter,
);
}
}
My Expected Get Response of Bus =>
{
" id":1,
"stations":[
{
"id":1,
"busId":1,
"name":"Station 1"
}
]
}
I did the exactly same with the documentation but why I can't get the response as I expected. Please May I know what I am missing?
I saw that some solution is to create another controller to connect these two models. Is it the only way? if yes, what is the reason for the hasMany?
in repository you have to include inclusion resolver under
this.stations = this.createHasManyRepositoryFactoryFor('stations',busStationnRepositoryGetter,);
like this
this.registerInclusionResolver('stations', this.stations.inclusionResolver);
on the other hand, you can use relation generator to avoid all this stuff.

How to retrieve dropdown items from an observable?

How would you retrieve dropdown items from an observable in #rxweb/reactive-dynamic-forms ?
how do you inject service in FormControlConfig subclass? shared code here https://stackblitz.com/edit/angular-bs5yqt-nmzcwj
For injecting custom services into the dynamic form control source model you have to pass the respective service into the argument of model configuration.
Step 1
Create a Service according to your need, I am creating fake ConfigService.
import { HttpClient} from "#angular/common/http"
import { Injectable } from "#angular/core"
#Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
configUrl = 'assets/config.json';
getConfig() {
return this.http.get(this.configUrl);
}
}
Step 2
Let's create a Model, which is extended with FormControlConfig for async source binding.
import { FormControlConfig } from "#rxweb/reactive-dynamic-forms"
import { ConfigService } from "./config.service"
export class SourceAsyncConditionalModel extends FormControlConfig{
constructor(fieldConfig: { [key: string]: any }, public controlsConfig: { [key: string]: FormControlConfig },notificationId:number,private configService:ConfigService){
super(fieldConfig,controlsConfig,notificationId);
}
filter() {
let promise = new Promise<any>((resolve, reject) => {
/// call the service
if(this.configService)
this.configService.getConfig();
});
}
}
If you see the above the code where I have defined four parameters. The first three parameters are used in FormControlControl and the fourth parameter we can use in the model instance.
Step 3
Now, we have to pass the parameter with respective model. See the below code :
this.dynamicFormConfiguration = {
controlConfigModels: [{ modelName: 'sourceAsync', model: SourceAsyncConditionalModel,arguments:[this.configService] }],
}
this.dynamicFormBuildConfig = this.formBuilder.formGroup(this.serverData, this.dynamicFormConfiguration);
Here is the working Example

Pass parameters between routes in nativesscript

In a NativeScript app I have two routes as bellow :
{ path : "boxes" , component : BoxesPage } ,
{ path : "card" , component : CardPage } ,
In the BoxesPage I'm trying to pass something to CardPage like this :
constructor ( private _routerExtention : RouterExtensions , private _router : Router) {
}
onItemTap ( _box ) {
let navigationExtras : NavigationExtras = {
queryParams : { 'box' : _box } ,
fragment : 'anchor'
};
this._router.navigate( [ '/card' ] , navigationExtras );
}
Then in the CardPage component :
ngOnInit () : any {
this.route.params.subscribe( ( _box : Box ) => {
console.log( _box ); //undefined or {}
} );
return undefined;
}
Question is :
Is this the right way ?
How should I get my box object inside the CardPage ?
Worth mentioning that I'm using Angular2 withing the NativScript.
I've tried everything but the documentation is extremely poor unfortunately.
Thanks in advance.
if you want to pass complex data(Object) between one component to other component stringify the object and pass it to other component to parse JSON by using object.
app.component.ts:
public appListComponent(item: any) {
const getData: string = item;
const navigationExtras: NavigationExtras = {
queryParams: {
DataList: JSON.stringify(getData)
}
};
this.routerExtensions.navigate(["app-modal"], navigationExtras);
}
app.modal.component.ts:
public constructor(public route: ActivatedRoute) {
this.route.queryParams.subscribe((params) => {
this.getParamData = params["DataList"];
let obj: ModalData = JSON.parse(this.getParamData);
console.log("Name", obj.name);
console.log("Description", obj.description);
});
}
modaldata.ts:
export class ModalData {
name: string;
description: string;
}
You can refer my answer in this similar post: NativeScript + Angular Navigation context . Basically you do this via "route arguments" which are strings. Unfortunately you cannot pass "entire" JS/TS objects but you can implements a service which can retrieve those via the provided string arguments. For roe details and code snippets check my response in the other thread.
Here is a short intro if the other thread:
Passing objects while navigating in Angular + NativeScript is not the same as vanila NativeScript. The routing is entirely implemented via angular specifications which means you will need to use their implementation. The current RC5 version of Angular 2 uses the following navigation (routing).

JayData Data model already created - add an OData action afterwards

I have an OData Web Api service where I create the controllers with a T4 template from the EF datamodel.
While doing that, I also create the Jaydata datamodel with T4.
But now, I have a partial class that will add an action to one of my controllers.
As the JayData file is also created by a T4 template, is there a way to add actions to one of the EntitySets later on?
What I managed to do now is the following:
My generated JayData context looks like the following:
$data.EntityContext.extend('myNameSpace.MyContext', {
'Cases': { type: $data.EntitySet, elementType: myNameSpace.Case},
// ... other Entitysets
}
Later, I extend this context like this:
myNameSpace.MyContext.extend('myNameSpace.MyExtendedContext', {
'Cases': { type: $data.EntitySet, elementType: myNameSpace.Case, actions: {
'Checkout': { type: $data.ServiceAction, returnType: 'myNameSpace.Case', IsBindable: true, 'EntitySet': 'Cases', IsAlwaysBindable: true, params: [{ name: 'Id', type: 'Edm.Guid' }] }
}
}
So I can use my action if I later use my extended context. I think this should be good enough.
My Typescript definitions for this look like this:
declare module myNamespace {
export class CaseExtensions extends $data.EntitySet<myNamespace.Case> {
Checkout: {
(Id: string, handler?: (result: myNamespace.Case) => void): $data.IPromise<Case>;
(params?: { Id?: string; }, handler?: (result: myNamespace.Case) => void): $data.IPromise<Case>;
};
}
export class MyExtendedContext extends MyContext {
Cases: CaseExtensions;
}
}

Resources