Nativescript/angular listpicker does not show array list - html

I am trying to get JSON data from server and then output the data in Nativescript Listpicker.I am also using Angular Here is the code.The problem is I cannot see the items displayed in the Listpicker.A service is being used to make an http request to the server. A subscription is used to get the data from the service. I have a play example below.I would like to know what I am doing wrong. Is it the event binding ?
JSON from server
[{'name':potato},{'name':berries}]
.ts file
import { Component, OnInit, OnDestroy, ChangeDetectionStrategy } from "#angular/core";
import { EventData} from 'tns-core-modules/data/observable';
import { RouterExtensions } from "nativescript-angular/router";
import { BehaviorSubject, Subscription } from "rxjs";
import { request, getFile, getImage, getJSON, getString } from "tns-core-modules/http";
import { Page } from 'ui/page';
import { Output_restaurants_service } from "../services/output_restaurants.service";
#Component({
selector: "item_option",
moduleId: module.id,
templateUrl: "./item_option.component.html",
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ["./item_option.component.css"]
})
export class ItemOption implements OnInit,OnDestroy {
page:Page;
args:EventData;
isLoading: boolean;
value:any;
picked:any;
cool:any;
list =[];
arr = [];
public pokemons: Array<string>;
private curChallengeSub: Subscription;
constructor(private service_men:Output_restaurants_service,page:Page, private router: RouterExtensions){
this.pokemons = [];
}
ngOnInit(){
this.service_men.output_included_sides().subscribe(
(r)=>{
for(let x =0;x<r.length;x++){
this.arr.push(r[x]['name']);
}
this.pokemons = this.arr;
console.log("observer"+ this.pokemons);
}
);
}
public selectedIndexChanged(picker) {
console.log('picker selection: ' + picker.selectedIndex);
this.picked = this.pokemons[picker.selectedIndex];
}
public onSelectedIndexChanged(picker) {
}
ngOnDestroy(){
}
}
Service
import { Injectable } from '#angular/core';
import { Http,Response} from '#angular/http';
import { HttpClient } from '#angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { map,tap,take } from "rxjs/operators";
import { Menu_i} from '~/restaurant_menu/restaurant.model';
import { Observable } from 'tns-core-modules/ui/page/page';
//import { Observable } from "rxjs";
#Injectable({providedIn:'root' })
export class Output_restaurants_service{
shopping_cart=[];
included_side_output:any;
menu_part:any;
menu_rest_items:any;
values:any
servers=[];
men:any;
menu_int= [];
outpuut_restaurants: any;
//response:string[]=[];
Restaurants:string[]=[];
countries: any[];
//http: any;
response = [];
pokemonsarray= [];
//private menuChanged = new Subject(null);
//public products: Observable<Menu[]>
private _currentChallenge = new BehaviorSubject(null);
constructor(private http:HttpClient) {
}
// sides(){
// return this._currentChallenge.asObservable();
// }
output_included_sides(){
this.included_side_output = this.http.get(`https://www.pidequehaypos.com/customer_chooses_food_type/output_specific_sides`);
return this.included_side_output;
}
add_variable_to_session(main_dish_id:string){
return this.http.post(`https://www.pidequehaypos.com/customer_chooses_food_type/store_main_dish_to_session`,{"main_dish_id":main_dish_id});
}
choose_restaurant() {
return this.http.get(`https://www.pidequehaypos.com/customer_chooses_business/output_businesses_button`);
}
post_menu_part_selected(restaurant_number:string){
this.menu_part= this.http.post(`https://www.pidequehaypos.com/customer_chooses_food_type/output_food_type`,{"business_id":restaurant_number});
return this.menu_part;
}
output_restaurant_items(menu_part_name:string){
this.menu_rest_items = this.http.post(`https://www.pidequehaypos.com/customer_chooses_food_type/output_food_and_drink_items`,{"menu_part_name":menu_part_name});
return this.menu_rest_items;
}
public set_restaurants (Rest){
//console.log("rest res"+Rest);
if(Rest["business"]){
// for(let t=0;t<Rest["business"].length;t++){
// this.restaurants.push(Rest["business"][t]["name"]);
// }
}
}
pes(){
//return this.menu.slice();
}
output_menu_items_test(){
return this.http.get<Menu_i>('https://www.pidequehaypos.com/customer_chooses_food_type/output_food_and_drink_items').pipe(take(1),
tap(resData => {
// tslint:disable-next-line:no-unused-expression
resData;
// tslint:disable-next-line: max-line-length
console.log('response from logout server ' + JSON.stringify(resData));
})
);
}
}
html file
<ListPicker #picker
id="pickerid"
class="p-15"
[items]="pokemons"
(selectedIndexChange)="onSelectedIndexChanged($event)">
</ListPicker>

Need to use async with the service.
ngOnInit() {
let items = [];
let subscr;
this.myItems = RxObservable.create(subscriber => {
subscr = subscriber;
subscriber.next(items);
return function () {
console.log("Unsubscribe called!");
};
});
this.service_men.output_included_sides().subscribe(
(r) => {
console.log("result: ", r)
for (let x = 0; x < r.length; x++) {
items.push(r[x]['name']);
subscr.next([...items]);
}
}
);
}
<ListPicker #picker id="pickerid" class="p-15" [items]="myItems | async"
(selectedIndexChange)="onSelectedIndexChanged($event)">
</ListPicker>
working example below
https://play.nativescript.org/?template=play-ng&id=zthg0B&v=54

Related

How to display product details when selecting a product using Realtime Database?

The code that I have at the moment is the same one that I use to show all the products of some category.
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { ProductosService } from '../../services/productos.service';
import { ProductoDescripcion } from '../../interfaces/producto-descripcion.interface';
#Component({
selector: 'app-comprar',
templateUrl: './comprar.component.html',
styleUrls: ['./comprar.component.css']
})
export class ComprarComponent implements OnInit {
cargando = true;
producto: ProductoDescripcion [] = [];
id:string;
constructor( private route: ActivatedRoute,
public ProductoService:ProductosService) {
}
ngOnInit(): void {
this.route.params
.subscribe(parametros => {
//console.log(parametros['id'])
this.ProductoService.getProducto(parametros['id'])
.subscribe( (producto: ProductoDescripcion [] )=> {
this.id = parametros ['id']
this.producto = producto;
console.log(producto)
this.cargando = false;
});
});
}
}
The problem is that when I click on a product, it returns the details of all those in the category.
My database is the following.
my products.service.ts, I have the option to load products and below the option to get the details of my products.
export class ProductosService {
cargando = true;
productos: Producto[] = [];
productosFiltrar:Producto[]=[];
constructor( private http: HttpClient ) {
this.cargarProductos();
}
private cargarProductos() {
return new Promise<void>( (resolve, reject)=>{
this.http.get<Producto[]>('https://angular-html-2b54e-default-rtdb.firebaseio.com/productos_idx.json')
.subscribe( (resp: Producto[]) => {
console.log(resp);
this.productos = resp;
this.cargando = false;
resolve();
});
});
}
getProducto(id:string) {
return this.http.get<ProductoDescripcion[]>(`https://angular-html-2b54e-default-rtdb.firebaseio.com/productos/${id}.json`)
}```

Angular, Displays a list multiple times on the same html page, that is updated each round of the loop through c#

I want to display a list as the options in select when in each round in the loop the list will be updated according to the current div
It works in terms of concept, but the html is updated only once according to the last entry in the list and does not display a different list for each loop rotation
my html
<div *ngFor="let item of listConstraint" [value]="item.id">
<p>{{item.name_constraint}}</p>
<select>
<option *ngFor="let item1 of listConstraintDetails" [value]="item1.id">
{{item1.name_constraint}}</option>
</select>
</div>
my ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { AjaxRequestService } from 'src/app/services/Request/ajax-request.service';
import { ConstraintKind } from 'src/app/class/constraintKind';
import { ConstraintDetails } from 'src/app/class/constraint-details';
#Component({
selector: 'app-constraints',
templateUrl: './constraints.component.html',
styleUrls: ['./constraints.component.css']
})
export class ConstraintsComponent implements OnInit {
constraintForm: FormGroup;
listConstraint: ConstraintKind[] = [];
listConstraintDetails: ConstraintDetails[] = [];
constructor(private http: AjaxRequestService, private httpClient: HttpClient, private route: Router) {
}
ngOnInit(): void {
this.GetConstraintsKind();
}
GetConstraintsKind() {
return this.http.GetConstraintsKind().subscribe(data => {
this.listConstraint = data;
data.forEach(element => {
this.GetConstraintsDetails(element.id);
})
console.log(data);
})
}
GetConstraintsDetails(constraintId) {
return this.http.GetConstraintsDetails(constraintId).subscribe(data => {
this.listConstraintDetails = data;
console.log(data);
})
}
}
my functions ajax service
GetConstraintsKind() {
return this.http.get<any>('http://localhost:11818/Api/Constraint/getConstraintKind', { headers: this.header });
}
GetConstraintsDetails(constraintId: number) {
return this.http.get<ConstraintDetails[]>('http://localhost:11818/Api/Constraint/GetConstraintsDetails/' + constraintId);
}
the server works well, and send the correct data, but the html display the same list the whole time
Thanks so much for any help
You are performing inner loop operation all at ngOnInit inside a single array, thats overwriting previously fetched data in the listConstraintDetails array.
What you want can be achieved, if you modify your code a little, like this
ngOnInit(): void {
this.GetConstraintsKind();
}
GetConstraintsKind() {
return this.http.GetConstraintsKind().subscribe(data => {
this.listConstraint = data;
})
}
GetConstraintsDetails(constraintId):ConstraintDetails[]{
let itemsarr: ConstraintDetails[] = [];
if(constraintId)
{
this.http.GetConstraintsDetails(constraintId).subscribe(data => {
itemsarr = data;
})
}
return itemsarr;
}
And your html would get modified like
<div *ngFor="let item of listConstraint" [value]="item.id">
<p>{{item.name_constraint}}</p>
<select>
<option *ngFor="let item1 of GetConstraintsDetails(item.id)" [value]="item1.id">
{{item1.name_constraint}}</option>
</select>
</div>
Thanks.
my html
<div *ngFor="let item of listConstraint" [attr.data-value]="item.id">
<p>{{item.name_constraint}}</p>
<select *ngIf="constraintDetails[item.id]">
<option *ngFor="let item1 of constraintDetails[item.id]" [value]="item1.id">
{{item1.name_constraint}}</option>
</select>
</div>
my ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { AjaxRequestService } from 'src/app/services/Request/ajax-request.service';
import { ConstraintKind } from 'src/app/class/constraintKind';
import { ConstraintDetails } from 'src/app/class/constraint-details';
import { Observable } from 'rxjs';
#Component({
selector: 'app-constraints',
templateUrl: './constraints.component.html',
styleUrls: ['./constraints.component.css']
})
export class ConstraintsComponent implements OnInit {
constraintForm: FormGroup;
listConstraint: ConstraintKind[] = [];
listConstraintDetails: ConstraintDetails[] = [];
constraintDetails = {};
constructor(private http: AjaxRequestService, private httpClient: HttpClient, private route: Router) {
}
ngOnInit(): void {
this.GetConstraintsKind();
}
GetConstraintsKind() {
return this.http.GetConstraintsKind().subscribe(data => {
this.listConstraint = data;
for (let i = 0; i < this.listConstraint.length; i++) {
const element = this.listConstraint[i].id;
this.http.GetConstraintsDetails(element)
.subscribe(cd => {
this.constraintDetails[element] = cd;
console.log(this.constraintDetails)
});
}
})
}
GetConstraintsDetails(constraintId): ConstraintDetails[] {
console.log(constraintId);
let itemsarr: ConstraintDetails[] = [];
if (!itemsarr) {
this.http.GetConstraintsDetails(constraintId).subscribe(data => {
itemsarr = data;
})
}
return itemsarr;
}
}

Can we set the APP_BASE_HREF in angular 6 dynamically by getting the value from http call in a service?

This is the code from app.module.ts file
{
provide: APP_BASE_HREF,
useFactory: referalCodeValidator,
deps: [ValidatorService]
}
There is a referalCodeValidator function defined in the app.module.ts file itself
export function referalCodeValidator(common: ValidatorService) {
let path = location.pathname;
let refCode = path.split("/", 2);
return common.validateReferralCode(refCode[1]);
}
The validator service is as follows:
import { Injectable } from "#angular/core";
import { Observable } from "rxjs";
import { environment } from "../../environments/environment";
import { HttpClient } from "#angular/common/http";
import { tap, catchError } from "rxjs/operators";
#Injectable()
export class ValidatorService {
appBaseHref: any;
constructor(private http: HttpClient) {}
validateReferralCode(refCode): Observable<any> {
if (refCode != "" || refCode != null) {
this.appBaseHref = null;
return this.http
.get(someurl, {
params: {
referenceCode: refCode
}
})
.pipe(catchError((error, caught) => {
console.log(error);
throw error.error;
}) as any);
}
}
}

Data are not showing when two api called in` iondidenter`

I have one screen, which have two gridview . each grid view will populate some value after api calling. so my page will have 2 api calling. so when i call my api call method under constructor or ionViewDidEnter its not working. it allowing only one method to exeute.
here is my two api call method on one page .ts
Even i put under my constructor. But its not showing the data. so if i want to call the both api and need to display the data means how can i do that.please help me out. i was not able to find it out !!
Thanks in advance
updated:
import { Component, ViewChild } from '#angular/core';
import { AlertController, App, FabContainer, ItemSliding, List, ModalController, NavController, ToastController, LoadingController, Refresher } from 'ionic-angular';
import { CategoryDetailPage } from '../categorydetail/categorydetail';
import { ConferenceData } from '../../providers/conference-data';
import { UserData } from '../../providers/user-data';
import { SessionDetailPage } from '../session-detail/session-detail';
import { ScheduleFilterPage } from '../schedule-filter/schedule-filter';
import {Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from '../../providers/AuthService';
#Component({
selector: 'page-speaker-list',
templateUrl: 'speaker-list.html'
})
export class SpeakerListPage {
loading: any;
data: any;
Catdata: any;
Catdatanames: any;
resdata: any;
resCatdata: any;
resCatdatanames: any;
loginData: {username?: string} = {};
resloginData: {username?: string} = {};
constructor(
public alertCtrl: AlertController,
public app: App,
public loadingCtrl: LoadingController,
public modalCtrl: ModalController,
public navCtrl: NavController,
public toastCtrl: ToastController,
public confData: ConferenceData,
public user: UserData,
public http:Http,
public authService: AuthService
) {
}
ionViewDidEnter() {
this.show();
this.another();
}
show() {
this.showLoader();
this.authService.subs(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
if(this.data.status == 1)
{
this.Catdata = this.data.SubjectList;
//this.Catdata.forEach(category => console.log(category.CatID));
for(let i=0; i<this.Catdata.length; i++) {
// console.log(this.Catdata[i].SubjectName);
}
}
else if(this.data.status == 0) {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: 'Please Enter Valid Username & Password',
buttons: ['OK']
});
alert.present();
}
}, (err) => {
this.loading.dismiss();
});
}
another() {
this.authService.allresources(this.resloginData).then((result) => {
this.resdata = result;
if(this.resdata.status == 1)
{
this.resCatdata = this.resdata.SubjectList;
for(let i=0; i<this.resCatdata.length; i++) {
// console.log(this.resCatdata[i].FileName);
}
}
else if(this.resdata.status == 0) {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: 'Please Enter Valid Username & Password',
buttons: ['OK']
});
alert.present();
}
}, (err) => {
});
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Authenticating...'
});
this.loading.present();
}
}

Loading JSON data gives undefined object in Angular 2 - asynchronous?

...component.ts:
import { Component } from '#angular/core';
import { ValgteSkolerService } from '../valgteSkoler.service';
import { DatoService } from './datoer.service';
#Component({
selector: 'kalender',
providers: [DatoService],
templateUrl: 'app/kalendervisning/html/kalender.html'
})
export class KalenderComponent {
private valgteSkoleRuter: Array<any> = [];
public datoer: any[] = [];
constructor(private valgteSkolerService: ValgteSkolerService, private DatoService: DatoService) {
this.DatoService
.getDato()
.subscribe(datoer => { this.datoer = datoer; });
}
ngOnInit() {
this.valgteSkolerService.hentLagretData();
this.valgteSkoleRuter = this.valgteSkolerService.delteValgteSkoleRuter;
}
antallRuter: number = 0;
j: number = 0;
ukeEn(mnd: number, aar: number) :Cell[] {
var cells: Array<Cell> = [];
this.antallRuter = 0;
for (this.j = 1; this.j <= this.antallDager(mnd, aar); this.j++) {
var cell = new Cell;
console.log(this.datoer[this.j].dato);
cell.id = this.datoer[this.j].dato;
cell.text = this.j;
cells.push(cell);
this.antallRuter++;
this.j = this.j;
if (this.antallRuter % 7 == 0 && this.antallRuter != 0) {
break;
}
}
return cells;
}
class Cell {
id: string;
text: number;
}
...service.ts:
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class DatoService {
dato: Array<any>;
constructor(private http: Http) {}
getDato() {
return this.http.request('app/kalendervisning/datoer.json')
.map(res => res.json());
}
}
...json:
{
"dato": "2016-08-01"
},
etc.
I am struggling with the cell.id = this.datoer[this.j].dato statement in the component.
I have checked the browser inspector, and it seems like the datoer array is undefined until the whole code has been run through several times. After a while, the array gets filled up. When I tested this with console.log, it prints 9 undefined objects, and then the actual data, but for some reason repeated 2 times also.
I think there might be a problem that the data is not loaded asynchronously, but I'm not sure.
Are there any ideas why it acts like this, and do you have a solution?
add constrctor code of calling API inside ngOnInit :
ngOnInit() {
this.DatoService
.getDato()
.subscribe(datoer => { this.datoer = datoer; });
this.valgteSkolerService.hentLagretData();
this.valgteSkoleRuter = this.valgteSkolerService.delteValgteSkoleRuter;
}