ion slider not working in ModalController ionic 4 - ionic-framework

Version:
Cordova: cordova-lib#8.1.1
Ionic: 6.10.1
Error : this.slider.update is not a function
in .ts
import { ModalController, IonSlides } from "#ionic/angular";
trainingSliderOpts = {
speed: 400,
initialSlide: 0,
preloadImages: true,
allowTouchMove: false,
};
result: any;
#ViewChild("trainingSlider", { static: true }) slider: IonSlides;
ionViewDidEnter() {
this.slider.update();
}

Try to add a .then function at the end like that:
this.ionSlides.update().then(() =>
console.log('updated'))
}
If not working try the following on top of your your class:
#ViewChild('slider', {read: ElementRef})slider: ElementRef;
and then call it like this:
this.slider.nativeElement.update();

Related

Angular 10 ag-grid cannot set property 'setRowData' because gridOptions.api undefined

I am using following versions.
Angular CLI: 10.0.1
Node: 12.18.2
OS: win32 x64
Angular: 10.0.2
#ag-grid-community/angular#23.2.1
#ag-grid-community/all-modules#23.2.1
I am using the following way:
import { Component, OnInit, ViewChild, Output } from '#angular/core';
import { SummaryDataService } from '../services/data/summary-data.service';
import {AgGridService} from '../services/common/ag-grid.service';
import { UtilService } from '../services/common/util.service';
import { GridOptions } from '#ag-grid-community/all-modules';
import { FilterComponent } from '../common/filter/filter.component';
#Component({
selector: 'app-summary',
templateUrl: './summary.component.html',
styleUrls: ['./summary.component.css']
})
export class SummaryComponent implements OnInit {
errorMessage: any = null;
noResults: boolean;
summaryData: Array<any>;
columnDefs: any;
defaultColWidth: number = 200;
numberColWidth: number = 120;
defaultColDef: any;
innerHeight: any;
gridOptions: GridOptions;
test: any;
currentDateTo: string;
currentDateFrom: string;
pendingRequest: any;
constructor(
private summaryService: SummaryDataService,
private agGridServ: AgGridService,
private util: UtilService,
) {
this.innerHeight = 450;
this.errorMessage = null;
}
ngOnInit(): void {
this.noResults = false;
this.gridOptions = <GridOptions> {
columnDefs: this.createColumnDefs(),
onGridReady: () => {
this.gridOptions.api.sizeColumnsToFit();
},
rowHeight: 48,
headerHeight: 48,
pivotMode: true,
enableSorting: true,
enableColResize: true,
enableFilter: true,
showToolPanel: true,
enableRangeSelection: true,
sortingOrder: ['asc', 'desc'],
suppressAggFuncInHeader: true,
suppressCopyRowsToClipboard: true,
filter: 'text'
}
}
private createColumnDefs() {
return [
{
headerName: "Name",
field: "name",
width: this.defaultColWidth,
sortable: true,
resizable: true,
filter: true
},
{
// Other columns definition
}
];
}
handleUserSelection(selection) {
this.getSummaryData();
}
getSummaryData(selections: any): void {
this.summaryData = []
this.errorMessage = null;
this.noResults = false;
this.summaryService.loadSummaryData()
.subscribe (
data => {
this.summaryData = data;
this.noResults = this.summaryData.length === 0;
if(!this.gridOptions.api){
return;
}
this.gridOptions.api.setRowData(this.summaryData);
},
error => {
this.errorMessage = <any>error;
}
);
}
}
When I see the Network tab on chrome deveoper tools, the result is returned fine from the service.
The issue is at:
if(!this.gridOptions.api){
return;
}
Basically, in ngOnInit(), I am initializing the gridOptions (GridOptions); but my data is to be fetched later (based on some checks and user input).
So when I am trying to use setRowData, it fails as this.gridOptions.api is undefined.
How can I solve this?
Try setting up the api after grid initialisation.
You have to use the method onGridReady(params). You can get gridApi from the params like params.api
You have to use it as following. When the grid finished creating, it raises an event that it is ready. The event executes a function assigned to that event as seeing in the following code. According to Grid Event documentation page, the AgGridEvent has two properties, api, and columnApi. So you can take this property through the raised event's parameter, like params.api. You can assign this to whatever you want. Api property is needed to create, update, retrieve rows from the grid.
─ AgGridEvent
│ api: GridAPI, // see Grid API
│ columnApi: ColumnAPI // see Column API
Codes
<!-- IN HTML PAGE -->
<ag-grid-angular
(gridReady)='onGridReady($event)'>
</ag-grid-angular>
// in TYPE SCRIPT File
onGridReady(params: any) {
this.gridApi = params.api;
}
Actually if you still has the issue, you should paste the code where you call handleUserSelection method.
BTW, you code has an explicit issue, which may cause this.gridOptions undefined:
this.summaryService.loadSummaryData()
.subscribe (...)
You forgot to unsubscribe the observer, which may cause the issue and memory leak.

App crash when call camera preview plugin in socket.on function ionic 3

I want to get picture when receive event by socket by using native CameraPreview Cardova Plugin for ionic 3.
I use socket.io-client for socket
Problem: when app receive the event form server the app crash without give me any error data.
This my code:
import { HomePage } from '../home/home';
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { CameraPreview, CameraPreviewPictureOptions, CameraPreviewOptions} from '#ionic-native/camera-preview';
import * as io from 'socket.io-client';
export class HomePage {
socket:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public cameraPreview:CameraPreview) {
this.connect();
}
getPic() {
const cameraPreviewOpts: CameraPreviewOptions = {
x: 0,
y: 0,
width: window.screen.width,
height: window.screen.height,
camera: 'front',
tapPhoto: false,
previewDrag: false,
toBack: false,
alpha: 1
};
// picture options
const pictureOpts: CameraPreviewPictureOptions = {
width: 1200,
height: 1600,
quality: 50
}
console.log('before camera start')
// Crash here
this.cameraPreview.startCamera(cameraPreviewOpts).then(
(res) => {
console.log("start Cam");
let picture;
// take a picture
this.cameraPreview.takePicture(pictureOpts).then((imageData) => {
picture = 'data:image/jpeg;base64,' + imageData;
this.releaseCamera();
}, (err) => {
console.log(err);
});
},
(err) => {
console.log(err)
}).catch(e=>console.log(e));
}
connect(){
this.socket=io('http://localhost:22222',{reconnectionDelay:5000, reconnectionDelayMax:999999999});
this.socket.on('order',(data)=>{
let order = data.order;
let extra = data.extra;
switch (order) {
case "x0000ca":
if (extra=="0"){
this.getPic();
//this.socket.emit("x0000ca" , obj);
});
}
break;
}
})
}
Ionic Framework : ionic-angular 3.9.2
#ionic/app-scripts : 3.2.0
Ionic Framework : ionic-angular 3.9.2
#ionic/app-scripts : 3.2.0
I wish find solution for this problem.

IONIC 2 - Cannot retrieve array inside ionViewDidLoad()

I want to retrieve places coordinates from restApi and display them on the map.
I got error : Cannot read property 'length' of undefined
Please help me !
I want you to tell me how i can get my data in order to add multiple markers.
This is my portion of code
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import { RestProvider } from '../../providers/rest/rest';
declare var google;
#Component({
selector: 'page-localisation',
templateUrl: 'localisation.html',
})
export class LocalisationPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
places: Array<any>;
errorMessage : string;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation, public rest: RestProvider) {
}
ionViewDidLoad(){
this.loadMap();
this.getPlaces();
this.addPlacesToMap()
console.log("Length : " + this.places.length) ; //Error Cannot read property 'length' of undefined
}
getPlaces() {
this.rest.getPlaces().subscribe(
places => this.places = places,
error => this.errorMessage = <any>error
);
}
loadMap(){
let latLng = new google.maps.LatLng(-4.066548, 5.356315);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
addPlacesToMap(){
//...
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
});
content: content
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}
ionViewDidLoad is launched before "this.rest.getPlaces().subscribe" is finished... So your variable "places" is NULL
Change getPlaces to a Promise
async getPlaces() {
places = await this.rest.getPlaces() ;
return places
}
Then in ionViewDidLoad
ionViewDidLoad(){
var that = this ;
this.loadMap();
this.getPlaces().then((places)=>{
that.places = places;
console.log("Length : " + that.places.length) ;
});
this.addPlacesToMap()
}

Camera preview takePicture function not working Ionic?

I am trying to get the takePicture function to work and get the imageData, but no luck so far. I have tried the new Beta plugin Camera Preview, but that will not start the camera at all.
I have the plugin com.mbppower.camerapreview and npm install --save #ionic-native/camera-preview.
I just need to get the imageData from the takePicture, but don't know how?
This is the code:
import { Component, NgZone } from '#angular/core';
import { NavController, ToastController } from 'ionic-angular';
import firebase from 'firebase';
import { CameraPreview, CameraPreviewRect } from 'ionic-native';
import { Diagnostic } from 'ionic-native';
import { File } from 'ionic-native';
import { AlertProvider } from '../../providers/alertprovider';
import { ImageProvider } from '../../providers/imageprovider';
declare var cordova: any; // global variable for paths
#Component({
selector: 'page-upload',
templateUrl: 'upload.html'
})
export class UploadPage {
public user: any;
constructor(private nav: NavController, private zone:NgZone, private
cameraPreview: CameraPreview, public diagnostic: Diagnostic, public
toastCtrl: ToastController,
public imageProvider: ImageProvider, public alertProvider: AlertProvider){
}
ionViewDidEnter(){
this.checkPermissions();
}
ionViewWillLeave() {
CameraPreview.stopCamera();
}
checkPermissions() {
Diagnostic.isCameraAuthorized().then((authorized) => {
if(authorized)
this.initializePreview();
else {
Diagnostic.requestCameraAuthorization().then((status) => {
if(status == Diagnostic.permissionStatus.GRANTED)
this.initializePreview();
else {
// Permissions not granted
// Therefore, create and present toast
this.toastCtrl.create(
{
message: "Cannot access camera",
position: "bottom",
duration: 5000
}
).present();
}
});
}
});
}
initializePreview() {
// Make the width and height of the preview equal
// to the width and height of the app's window
let previewRect: CameraPreviewRect = {
x: 0,
y: 57,
width: window.innerWidth,
height: window.innerHeight/2
};
// More code goes here
// Start preview
CameraPreview.startCamera(
previewRect,
'rear',
true,
true,
false,
1
);
CameraPreview.setOnPictureTakenHandler().subscribe((imageData) => {
// Process the returned imageURI.
let imgBlob = this.imageProvider.imgURItoBlob("data:image/jpeg;base64," + imageData);
let metadata = {
'contentType': imgBlob.type
};
firebase.storage().ref().child('images/' + this.user.userId + '/cards' + '/' + this.imageProvider.generateFilename()).put(imgBlob, metadata).then((snapshot) => {
// URL of the uploaded image!
let url = snapshot.metadata.downloadURLs[0];
}).catch((error) => {
this.alertProvider.showErrorMessage('image/error-image-upload');
});
});
}
takePicture() {
CameraPreview.takePicture({maxWidth: 1280, maxHeight: 1280});
}
}
Cordova CLI: 6.5.0
Ionic Framework Version: 3.0.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.10.0
Xcode version: Not installed
Instead of this
// More code goes here
// Start preview
CameraPreview.startCamera(
previewRect,
'rear',
true,
true,
false,
1
)
use this make toBack false it will bring camera preview to the front.
// More code goes here
// Start preview
CameraPreview.startCamera(
previewRect,
'rear',
false,
true,
false,
1
)
if that does not solve your problem remove that camera plugin and use this latest one
ionic plugin add https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git
this has new fixes which are not available on npm yet.

Ionic 2 Slides Component - How to Access Swiper API

Using ion-slides component (4 slides) on app welcome page/slides. I need ability for user to skip to last slide. Docs say ion-slides implementation of Swiper API. I need to access methods like: mySwiper.slideTo(index, speed, runCallbacks);
Tips on how to implement?
You can pass a function within the options property.
Original answer.
#Component({
selector: 'my-component',
template: '<ion-slides [options]="options">
<ion-slide>Slide1</ion-slide>
<ion-slide>Slide2</ion-slide>
</ion-slides>',
directive: [IONIC_DIRECTIVES]
})
export class MyComponent {
public slider: any;
constructor() {
this.options = {
onlyExternal: false,
onInit: (slides: any) =>
this.slider = slides
}
}
click() {
this.slider.sliderNext(true, 250);
}
}
For further options have a look at the swiper api.
If you are looking for a simple solution without custom directives, you can try this
constructor(
private _app: IonicApp
){}
ngAfterViewInit() {
this._slider = this._app.getComponent('my-slider');
}
goToSlide(slideIndex){
this.slider.slider.slideTo(slideIndex);
}
You can make a service with your Swiper
#Injectable()
export class HomeSwiper {
swiper = null;
initSwiper(selector) {
this.swiper = new Swiper(selector, {
pagination: '.home-swiper-pagination',
speed: 400,
spaceBetween: 100,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev'
});
}
goTo(index) {
this.swiper.slideTo(index);
}
}
And use it into your #Page
#Page({
templateUrl: 'build/pages/home/home.html',
providers: [HomeSwiper]
})
export class Home {
constructor(private swiperService: HomeSwiper) {
this.swiperService.initSwiper('.home-modal-swiper-container');
}
skipSlides() {
this.swiperService.goTo(indexOfTheLastSlide);
}
}