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

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();
}
}

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`)
}```

Nativescript/angular listpicker does not show array list

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

How to get JSON data into Dialog Component

Before this, the JSON Data appears when hovering over the info icon. Now i wish to pass the JSON Data into a dialog when click the info icon. But i dont know how.
HTML
<h2 mat-dialog-title>Info</h2>
<mat-dialog-actions>
<button mat-button (click)="matDialogRef.close()">Ok</button>
</mat-dialog-actions>
Dialog-Component.ts
import { Component, OnInit, Input, Inject, ViewEncapsulation, HostListener } from '#angular/core';
import { MAT_DIALOG_DATA, MatDialogRef} from '#angular/material';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { PlannerProject } from 'app/services/planner-projects/planner-project';
#Component({
selector: 'app-my-dialog',
templateUrl: './my-dialog.component.html',
styleUrls: ['./my-dialog.component.scss']
})
export class MyDialogComponent implements OnInit {
#Input() project: PlannerProject;
projectData: string;
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
}
ngOnChanges(event): void {
if (event.project !== undefined) {
this.projectData = JSON.stringify(this.project, null, 2);
}
}
ok(): void {
this.matDialogRef.close();
}
}
Delivery-Order.Component.ts
import { DeliveryOrderEditComponent } from './../delivery-order-edit/delivery-order-edit.component';
import { SelectionModel } from '#angular/cdk/collections';
import { Component, OnInit, ViewChild, OnDestroy, ElementRef, Input, OnChanges } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { PlannerProjectsService } from 'app/services/planner-projects/planner-projects.service';
import { map, switchMap, tap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { DeliveryOrdersService } from '../delivery-orders.service';
import { Observable, of, Subscription, fromEvent } from 'rxjs';
import * as moment from 'moment';
import { MatPaginator, MatSort, PageEvent, MatTableDataSource, MatDialog } from '#angular/material';
import * as _ from 'lodash';
import { FuseSidebarService } from '#fuse/components/sidebar/sidebar.service';
import { DeliveryOrder } from '../delivery-order';
import { MyDialogComponent } from './../my-dialog/my-dialog.component';
import { PlannerProject } from 'app/services/planner-projects/planner-project';
import { FuseConfirmDialogComponent } from '#fuse/components/confirm-dialog/confirm-dialog.component';
import { UploadExcelService } from 'app/services/upload-excel.service';
#Component({
selector: 'app-delivery-orders',
templateUrl: './delivery-orders.component.html',
styleUrls: ['./delivery-orders.component.scss']
})
export class DeliveryOrdersComponent implements OnInit, OnDestroy, OnChanges {
#Input() project: PlannerProject;
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
selection: SelectionModel<DeliveryOrder>;
importId: string;
dataTable;
sub: Subscription;
projectData : string;
// _filter: string;
_sortBy: string;
_sortOrder = 'asc';
_pageSize = 10;
_pageIndex = 1;
_options = {
pageSize: 100,
pageSizeOptions: [100, 150, 200, 250]
};
_displayedColumns = [
{ displayName: 'Location Name', column: 'locationName', sort: true },
{ displayName: 'Delivery Address', column: 'address', sort: false },
{ displayName: 'Is Valid', column: 'isValid', sort: false },
{ displayName: 'Import At', column: 'importedAt', sort: false },
{ displayName: 'File Name', column: 'importFileName', sort: false },
// { displayName: '', column: '' },
// { displayName: '', column: '' },
];
_displayColumns: string[] = ['selectRow', 'locationName', 'address', 'quantity', 'weight', 'volume', 'remarks', 'importedAt', 'actions'];
_actions = [
{
text: 'Edit',
action: (row) => {
console.log(`row`, row);
}
}
];
_dataSource: MatTableDataSource<DeliveryOrder>; // = new DeliveryOrdersDataSource(this.deliveryOrderService, '');
_filter: string | Observable<string>;
// #ViewChild('listHeader') listHeader: PageListTemplateComponent;
#ViewChild('search') search: ElementRef;
constructor(private route: ActivatedRoute,
private router: Router,
private projectService: PlannerProjectsService,
private deliveryOrderService: DeliveryOrdersService,
private uploadExcelService: UploadExcelService,
private _matDialog: MatDialog) { }
openDialog(): void {
const Ref = this._matDialog.open(MyDialogComponent, {
});
Ref.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result);
});
}
ngOnInit(): void {
this.initDataTable();
}
ngOnDestroy(): void {
console.log(`destroy`);
if (this.sub) {
this.sub.unsubscribe();
}
}
ngOnChanges(): void {
if (this.project !== undefined) {
this.projectData = JSON.stringify(this.project, null, 2);
this.loadList(this.project.importId).toPromise().then((data) => {
console.log(`data`, data);
_.map(data, this.formatData.bind(this));
this.dataTable = data;
this._dataSource.data = this.dataTable;
this.selection = new SelectionModel<DeliveryOrder>(true, []);
});
}
So when i click the info icon, it shall display the JSON data in the dialog box. i also added the Delivery-order.component. I dont know much about JSON, so im very weak in trying to solve this problem to make the JSON values show up
When you create your dialog in delivery-component you can define input data for your dialog component, in this way:
const Ref = this._matDialog.open(MyDialogComponent, {
data: { id: 'id-value' }
});
Then you can recover your data in your dialog component:
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(this.data.id);
}
In this example this.data will contain the data passed from your main component to dialog, the id field is only an example, you can pass whatever you want to dialog component.
Try something like this.
First method will open dialog and will pass all the data of the project
openDialog(): void {
const Ref = this._matDialog.open(MyDialogComponent, { data: this.project });
And in the dialog just use as the #Simo said
This will Inject the passed data from component to dialog
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(this.data);
}

Type 'Observable<DataListeItem[]>' is not assignable to type 'DataListeItem[]'

Full error message:
"Type 'Observable' is not assignable to type 'DataListeItem[]'.
Property 'includes' is missing in type 'Observable'."
I'm using material Table Schematic and now I want to fill the list from my Rest service.
data-liste-datasource.ts
import { DataSource } from '#angular/cdk/collections';
import { MatPaginator, MatSort } from '#angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { AuthService } from '../auth.service';
export interface DataListeItem {
name: string;
id: number;
email: string;
number: number;
}
export class DataListeDataSource extends DataSource<DataListeItem> {
data: DataListeItem[] = this.authservice.GetUser(); <-- error here!
constructor(private paginator: MatPaginator, private sort: MatSort, private authservice: AuthService) {
super();
}
connect(): Observable<DataListeItem[]> {
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
this.paginator.length = this.data.length;
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
disconnect() { }
private getPagedData(data: DataListeItem[]) {
const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
return data.splice(startIndex, this.paginator.pageSize);
}
private getSortedData(data: DataListeItem[]) {
if (!this.sort.active || this.sort.direction === '') {
return data;
}
return data.sort((a, b) => {
const isAsc = this.sort.direction === 'asc';
switch (this.sort.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'email': return compare(a.email, b.email, isAsc);
case 'id': return compare(+a.id, +b.id, isAsc);
case 'number': return compare(+a.number, +b.number, isAsc);
default: return 0;
}
});
}
}
function compare(a, b, isAsc) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
auth.service.ts
import { Injectable } from '#angular/core';
import { HttpHeaders, HttpClient } from '../../node_modules/#angular/common/http';
import { Observable } from '../../node_modules/rxjs';
import { DataListeItem } from './data-liste/data-liste-datasource';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
GetUser(): Observable<DataListeItem[]> {
return this.http.get<DataListeItem[]>("DataListeItem.online");
}
So all in all how to I make a call to my REST and get the list shown.
Should I make the call directly in " data-liste-datasource.ts" or should that be in the service.
thanks for reading
You need to use Observable<DataListeItem[]> instead of DataListeItem[].
data: Observable<DataListeItem[]> = this.authservice.GetUser();

Error: Cannot find module "./../providers/auth-service" [duplicate]

I am trying to create Login/SignUp in ionic angular 3.3.0.
I get the error Cannot find module '../providers/auth-service/auth-service'. in the login.ts file. Please Help!
auth-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
/*
Generated class for the AuthServiceProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
export class User {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}
#Injectable()
export class AuthServiceProvider {
currentUser: User;
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
// At this point make a request to your backend to make a real check!
let access = (credentials.password === "pass" && credentials.email === "email");
this.currentUser = new User('ian', 'ianlikono#gmail.com');
observer.next(access);
observer.complete();
});
}
}
public register(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
// At this point store the credentials to your backend!
return Observable.create(observer => {
observer.next(true);
observer.complete();
});
}
}
public getUserInfo() : User {
return this.currentUser;
}
public logout() {
return Observable.create(observer => {
this.currentUser = null;
observer.next(true);
observer.complete();
});
}
}
login.ts
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { AuthServiceProvider } from '../providers/auth-service/auth-service';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
loading: Loading;
registerCredentials = { email: '', password: '' };
constructor(private nav: NavController, private auth: AuthServiceProvider, private alertCtrl: AlertController, private loadingCtrl: LoadingController) { }
public createAccount() {
this.nav.push('RegisterPage');
}
public login() {
this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
this.nav.setRoot('HomePage');
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Please wait...',
dismissOnPageChange: true
});
this.loading.present();
}
showError(text) {
this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'Fail',
subTitle: text,
buttons: ['OK']
});
alert.present(prompt);
}
}
ScreenShot Program structure:
From your project structure, your login.ts is inside login folder, and login folder is inside pages folder.
So in order to reach providers folder, you need to write
'../../providers/auth-service/auth-service'
This should move you out of two folders which should solve the issue.
If you are using VS Code, install the plugin called "Typescript Hero" and "Typescript Toolbox", will help you with your imports.
Actually "Typescript Toolbox" shows a lightbulb when you focus your cursor on an imported element and you can select from the lightbulb the import. Very usefull.