infinte scroll with loading msg after 10 items - ionic-framework

I am displaying a list of items. I want, when we scroll, after displaying 10 items. it displays " loading more..."
(ionInfinite)="doInfinite($event)"
is not triggering.
.html file
<ion-content padding>
<ion-list>
<ion-item *ngFor="let i of items">{{i}}</ion-item>
</ion-list>
<ion-infinite-scroll (ionInfinite)="doInfinite($event)">
<ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data...">
</ion-infinite-scroll-content>
</ion-infinite-scroll>
</ion-content>
.ts file
import { IonInfiniteScroll, IonVirtualScroll } from '#ionic/angular';
export class FoodMenuPage implements OnInit {
#ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
items = [];
constructor() {
for (let i = 0; i < 30; i++) {
this.items.push( this.items.length );
}
}
doInfinite(infiniteScroll) {
console.log('Begin async operation');
setTimeout(() => {
for (let i = 0; i < 30; i++) {
this.items.push( this.items.length );
}
console.log('Async operation has ended');
infiniteScroll.complete();
}, 500);
}

HTML
<ion-infinite-scroll (ionInfinite)="doInfinite($event)">
<ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data...">
</ion-infinite-scroll-content>
<div *ngIf="pagingEnabled" class="nomore_data"> No more data is available.</div>
TS
if (this.image1 != 0) {
for (let i in this.image1) {
this.images = this.images.concat(this.image1[i]);
}
} else {
this.pagingEnabled = true;
} \\image1 and image have same json value
if (Infinitescroll) { \\every scroll infinite has been fire
Infinitescroll.target.complete();\\every scroll tarhas been completed
}
no need for viewchild or anything

Related

Search bar (ionInput) event to filter output

I am using search bar ionInput event to search among the list but filtered output is shown for one list and not shown for other list on other page?
my first list code :-
HTML
<ion-searchbar class="ion-no-padding" showcancelbutton="true" (ionInput)="onSearchChange($event)" placeholder="search manga"></ion-searchbar>
<ion-list no-lines *ngFor="let anime of animelist" >
<ion-item>
<h2>Name : {{anime.t}}</h2>
</ion-item>
</ion-list>
My .ts file
getanimelist(){
this.restProvider.getanimelist().subscribe(data => {
this.animelist = data;
console.log('result ' + JSON.stringify(data) );
});
this.items= this.animelist;
}
onSearchChange(evt: any) {
this.getanimelist();
console.log(this.items);
console.log(evt);
const val = evt.srcElement.value;
console.log(val);
if (!val){
return ;
}
this.animelist = this.items.filter((data) => {
// console.log(data);
if (data.t && val){
if (data.t.toLowerCase().indexOf(val.toLowerCase()) > -1){
return true;
}
return false;
}
})
}
my api call for this:-
apiUrl= 'https://www.mangaeden.com/api';
getanimelist(){
return this.http.get(this.apiUrl+'/list/0').pipe(
map(result => {
return result['manga'];
})
)}
}
the output for this list does get filter and my list do get updated on the page as per the value enterd but for my second list on other page iam using the same concept same code but my output is not getting filtered on the page, inside the console log i see the filtered result but my page list is not getting updated
second list code below :-
HTML
<ion-searchbar class="ion-no-padding" showcancelbutton="true" (ionInput)="onSearchChange($event)" placeholder="search manga"></ion-searchbar>
<ion-list no-lines *ngFor="let anime of animelist" >
<ion-item >
<h2>Name : {{anime.t}}</h2>
</ion-item>
</ion-list>
My .ts file
getanimelist(){
//this.isLoaded = true;
this.restProvider.getpageanimelist().subscribe(data => {
this.animelist = data;
//console.log('result ' + JSON.stringify(data) );
});
this.items= this.animelist;
}
onSearchChange(evt: any) {
this.getanimelist();
const val = evt.srcElement.value;
console.log(this.items);
console.log(evt);
console.log(val);
if (!val){
return ;
}
this.animelist = this.items.filter((data) => {
// console.log(data);
if (data.t && val){
if (data.t.toLowerCase().indexOf(val.toLowerCase()) > -1){
return true;
}
return false;
}
});
}
my api call for the 2nd list:-
getpageanimelist(){
return this.http.get(this.apiUrl+'/list/0/?p=0&l=26').pipe(
map(result => {
return result['manga'];
})
)}
hope someone can help why is the filtered result not shown for my 2nd list ?
I stored the filter data in a new array rather than in animelist array (which is getting data from the api in the subscribe block) which was causing the whole array to call again and hence no filtered data can be viewed
my changed code in .ts
onSearchChange(evt: any) {
this.getanimelist();
const val = evt.srcElement.value;
if (!val){
return ;
}
this.newarray = this.items.filter((data) => { //stored data in new array
if (data.t && val){
if (data.t.toLowerCase().indexOf(val.toLowerCase()) > -1){
return true;
}
return false;
}
})
}
and hence i call the new array in my html and now when i type the name of the anime the list get filtered accordingly without any issue.
Changed Html
<ion-searchbar class="ion-no-padding" showcancelbutton="true" (ionInput)="onSearchChange($event)" placeholder="search manga"></ion-searchbar>
<ion-list no-lines *ngFor="let anime of newarray" >
<ion-item >
<h2>Name : {{anime.t}}</h2>
</ion-item>
</ion-list>

How to filter the data from API json using ionic?

I would like to have a search bar that filters the results I tried to do it but it does not work. When I'm looking for something, nothing happens, no mistake, so I'm wrong, but I do not know what, I'm new to typescript and I ask for help. Thanks in advance
Home.html
---------
<ion-searchbar (ionInput)="filterItems()"
[showCancelButton]="shouldShowCancel" (ionCancel)="onCancel($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of items" (click)="itemClick(item.id)">
<h1>{{item.id}}</h1>
{{item.title}}
</ion-item>
</ion-list>
Home.ts
-------
export class HomePage {
public items:any;
constructor(public http:HttpClient) {
this.loadData();
}
searchTerm: string ;
loadData() {
let data:Observable<any>;
data = this.http.get('https://jsonplaceholder.typicode.com/photos');
data.subscribe(result => {
this.items = result;
this.filterItems= this.items;
})
}
filterItems(ev:any){
this.loadData();
const val = ev.target.value;
this.filterItems = this.items.filter(item =>
{
item.titre.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
})
}
itemClick(itemid:number){
alert(itemid);
}
}
so you can do this in your html
<ion-searchbar [formControl]="searchTerm"></ion-searchbar>
Then in your .ts file declare before the constructor
public searchTerm: FormControl;
Then inside your ngOnInit, have this function that listens to user input and waits a while before filtering
this.searchTerm.valueChanges
.pipe(debounceTime(700))
.subscribe(search => {
this.items = this.filterItems(search);
});
Then your final method for the filter
filterItems(search) {
this.items = this.filterItems;
return this.items.filter(item => {
return item.titre.toLowerCase().indexOf(search.toLowerCase()) > -1
});
}
I hope this helps

How to use ImagePicker to select image and display in Ionic Native

I'm developing an Ionic app, and one task is to select a profile via camera or gallery, and I use Ionic Native ImagePicker to select picture and crop, it can select and crop, but not display in front html page, my code is as below:
openImagePickerCrop(){
this.imagePicker.hasReadPermission().then(
(result) => {
if(result == false){
// no callbacks required as this opens a popup which returns async
this.imagePicker.requestReadPermission();
}
else if(result == true){
this.imagePicker.getPictures({
maximumImagesCount: 3
}).then(
(results) => {
for (var i = 0; i < results.length; i++) {
this.crop.crop(results[i], {quality: 100}).then(
newImage => {
this.imgResponse.push('data:image/jpeg;base64,' + newImage);
console.log("Image selected - " + newImage);
},
error => console.error("Error cropping image", error)
);
}
}, (err) => console.log(err)
);
}
}, (err) => {
console.log(err);
});
}
And this is my html code:
<ion-item class="input-item">
<ion-label position="floating">Photo</ion-label>
<div class='images' *ngFor="let img of imgResponse">
<img src="{{img}}" alt="" srcset="" />
</div>
<ion-card-content>
<ion-button color="medium" size="large" (click)="openImagePickerCrop()">
<ion-icon slot="icon-only" name="camera"></ion-icon>
</ion-button>
</ion-card-content>
</ion-item>
Where am I doing wrong, pls help.
Update:
To check if it's due to the crop function, I have updated functions as below:
openImagePicker(){
this.imagePicker.hasReadPermission().then(
(result) => {
if(result == false){
// no callbacks required as this opens a popup which returns async
this.imagePicker.requestReadPermission();
}
else if(result == true){
this.imagePicker.getPictures({
maximumImagesCount: 1
}).then(
(results) => {
for (var i = 0; i < results.length; i++) {
this.imgResponse.push('data:image/jpeg;base64,' + results[i]);
console.log("Image selected - " + results[i]);
}
}, (err) => console.log(err)
);
}
}, (err) => {
console.log(err);
});
}
But still not working, and the console doesn't capture anything.

Why not showing liked icon when page refresh in ionic

I am making like and dislike functionality in ionic app when user like then want to show heart icon and when user dislike then want to show empty heart icon.When like the post then icon show but when refreshing page then its show icon of empty likes.Please help me how to resolve this problem in ionic....
tab1.page.html
<div>
<img src="{{getImage.image}}" (click)="tapPhotoLike(getImage.id)" (click)="toggleIcon(getImage.id)">
</div>
<p no-margin no-padding>
<button clear ion-button icon-only class="like-btn">
<!-- <ion-icon no-padding name="like_btn.icon_name" color="{{ like_btn.color }}" class="icon-space"></ion-icon> -->
<ion-icon name="heart-empty" *ngIf="!iconToggle[getImage.id]" color="{{ like_btn.color }}"></ion-icon>
<ion-icon name="heart" *ngIf="iconToggle[getImage.id]" color="{{ like_btn.color }}"></ion-icon>
</button>
</p>
tab1.page.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
import { User } from '../user';
import { first } from 'rxjs/operators';
import { Storage } from '#ionic/storage';
import { ToastController } from '#ionic/angular';
import { LoadingController, NavController } from '#ionic/angular';
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
num
getImages: User[] = [];
getImages2: User[] = [];
getImages3 = [];
getcounts;
countLikes
counts
unlikes
likesID
iconToggle = [];
like_btn = {
color: 'danger',
icon_name: 'heart-empty'
};
public tap: number = 0;
public status: false;
constructor(private userService: UserService,
public toastController: ToastController,
private storage: Storage,
public navCtrl: NavController,
public loadingController: LoadingController) {
}
doRefresh(event) {
this.userPost();
setTimeout(() => {
event.target.complete();
}, 2000);
}
ngOnInit() {
this.userPost();
//this.getCountOfLikes();
}
async userPost() {
const loading = await this.loadingController.create({
message: 'Please wait...',
spinner: 'crescent',
duration: 2000
});
await loading.present();
this.userService.getUserPost().pipe(first()).subscribe(getImages => {
this.getImages3 = getImages;
loading.dismiss();
});
}
likeButton() {
const detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
let user_id = val
this.userService.userPostLikes(user_id, detail_id).pipe(first()).subscribe(
async data => {
this.iconToggle[this.num] = true;
if (data['status'] === 'you have already liked this post') {
const toast = await this.toastController.create({
message: 'you have already liked this post before.',
duration: 2000
});
toast.present();
}
this.userPost();
}
);
}
});
}
tapPhotoLike($detail_id, num) {
this.userService.setCurrentIdpostId($detail_id);
this.tap++;
setTimeout(() => {
if (this.tap == 1) {
this.tap = 0;
//this.unlikePost();
} if (this.tap > 1) {
this.tap = 0;
}
}, 250);
}
setIconToggles() {
let x = 0;
this.getImages3.forEach(() => {
this.iconToggle[x] = false;
x++;
});
}
toggleIcon(num) {
if (this.iconToggle[num]) {
this.iconToggle[num] = false;
this.unlikePost();
} else {
this.iconToggle[num] = true;
this.likeButton();
}
}
ionViewWillEnter() {
this.userPost();
}
unlikePost() {
let detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
let user_id = val;
this.userService.unLikes(user_id, detail_id).subscribe(async dislikes => {
this.unlikes = dislikes;
this.iconToggle[this.num] = false;
this.userPost();
})
}
});
}
}
How manage icon , i am inserting status on like and dislike in database..In this code how to manage status please help me.

How to reload/refresh with infinite-scroll

I want to have a reload function but I found some difficulties.
My app should clear all data by using the reload function and grab the feed again. Event that works, but it shows me only the first 5 news (limit of my api/per page) and ignores completely the loadMore function.
factory
.factory('newsDataService', function($http) {
return {
GetPosts: function(page) {
return $http.get("http://newsapi.domain.tdl/");
},
GetMorePosts: function(page) {
return $http.get("http://newsapi.domain.tdl/?page=" + page);
}
};
})
controller
.controller('NewsCtrl', function($scope, newsDataService) {
$scope.page = 1;
$scope.noMoreItemsAvailable = false;
newsDataService.GetPosts().then(function(items){
$scope.items = [];
$scope.items = items.data.response;
});
$scope.Reload = function() {
console.log('reload');
newsDataService.GetPosts().then(function(items){
console.log(items);
$scope.items = items.data.response ;
$scope.noMoreItemsAvailable = false;
$scope.$broadcast('scroll.refreshComplete');
})
};
$scope.loadMore = function(argument) {
$scope.page++;
newsDataService.GetMorePosts($scope.page).then(function(items){
if (items.data.response) {
$scope.items = $scope.items.concat(items.data.response);
$scope.noMoreItemsAvailable = false;
} else {
$scope.noMoreItemsAvailable = true;
}
}).finally(function() {
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
})
template:
<ion-view view-title="News">
<ion-content>
<ion-refresher on-refresh="Reload()"></ion-refresher>
<div class="list">
<a collection-repeat="news in items" href="#/app/newsreader/{{news.id}}" class="item item-thumbnail-left">
<h2>{{news.headline}}</h2>
<div class="item-text-wrap" ng-bind-html="news.teaser"></div>
</a>
</div>
<ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="1%"></ion-infinite-scroll>
</ion-content>
</ion-view>
How can I resolve this?
Just found the solution on my own.
.controller('NewsCtrl', function($scope, newsDataService) {
$scope.items =[]
$scope.page = 1;
newsDataService.GetPosts().then(function(items){
$scope.items = items.data.response;
});
$scope.Reload = function() {
console.log('reload');
$scope.items =[];
$scope.page = 1;
$scope.loadMore();
};
$scope.loadMore = function(argument) {
$scope.page++;
newsDataService.GetMorePosts($scope.page).then(function(items){
if (items.data.response) {
$scope.items = $scope.items.concat(items.data.response);
$scope.noMoreItemsAvailable = false;
} else {
$scope.noMoreItemsAvailable = true;
}
}).finally(function() {
$scope.$broadcast("scroll.infiniteScrollComplete");
$scope.$broadcast('scroll.refreshComplete');
});
};
})