I am trying to fetch data asynchronously twitter rest API (fetching my tweets to be more specific), and after I do so, I display them as cards. My problem is when I delete a tweet, it does not reflect in my application.
here's a part of my code:
Twitter service provider.
fetchDataFromTwitter() {
return this.httpReader = this.http.get('url').map((resp) => resp).catch((err: any) => {
return Observable.of(undefined);
});
}
twitterList page
public dataFromTwitter:any;
ionViewDidLoad() {
this.tweetProvider.fetchDataFromTwitter().subscribe((data: any) => {
..
..
..
some string manuplation..and iterate threw array of tweets
this.dataFromTwitter.push({
screenName:tweet.user.screen_name,
placeOfId: tweet.full_text.slice(indexStart, indexEnd),
userId: tweet.full_text.slice(indexStartForToken,indexEndForToken)
})
});
}
in the view for the twitterList.html page
<ion-content padding>
<div *ngIf="dataFromTwitter">
<ion-card *ngFor="let data of dataFromTwitter">
<ion-item>
<h2 >user: {{data .placeOfId }}</h2>
</ion-item>
<p>token: {{data.userId}}</p>
<ion-item>
</ion-content>
the example might have errors but, but I hope the idea is clear.
In order to refresh the list after deleting an item, you could choose any one of the following methods
On deleting an element, call the get item call again to refresh the list
Remove(splice) the element from the data source array, this will block the data from showing in the UI.
I will suggest the second one be better.
Maybe you can try this one
Create ion-refresher for your .html files
<ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-refresher-content pullingIcon="arrow-dropdown" pullingText="Pull to refresh" refreshingSpinner="circles"
refreshingText="Refreshing...">
</ion-refresher-content>
Create doRefresh() method on .ts
data: any; // contain array of my data
ngOnInit() {
this.dataSampah();
}
async dataSampah() {
this.session_storage().then(() => {
this.postPrvdr.getData(`tps/invoice?id_tps=` + this.id_tps).subscribe(res => {
this.data = res.data;
}, err => {
console.log(err);
});
});
}
doRefresh(event) {
this.data = null; // this is replacement of splice
this.ngOnInit(); //
setTimeout(() => {
this.router.navigate(['/invoice-sampah']);
event.target.complete();
}, 2000);
Related
I'm using Ionic and Firestore for my web appllication. In a component I show a list of items from firestore database,the detail of an item in url tabs/items/list-detail/ and other button to modify images, then there is a button to return the url tabs/items/. Afterwards, if I return to the tabs/items/list-detail page I would like the list to be reloaded with the modified items, but the page remains the same.
I have tried using ViewWillEnter but doesn't work.
In html page of items there is a button to navigate to detail page:
<ion-button id="detail" *ngIf="registeredAndUpl?.registered!=true" [routerLink]="['/tabs/items/list-detail',id]">View</ion-button>
This is the component list-detail Page:
export class DetailPage implements OnInit, ViewWillEnter {
items: any
userId: any
item0: any
item1: any
constructor(private route: ActivatedRoute, private router: Router,
public authService: AuthenticationService,
) {}
ngOnInit() {
}
ionViewWillEnter() {
this.myDefaultMethodToFetchData();
}
myDefaultMethodToFetchData() {
console.log("IN")
this.getItems().then((data) => {
console.log("IN2222")
this.items = data
this.item0 = this.items[0];
this.item1 = this.items[1];
})
this.userId = this.authService.userData.uid;
}
returnItems(){
this.router.navigate(['/tabs/items/']);
}
getItems() {
const itemsRef = firebase.firestore().collection("user_orders/" + this.userId+"/reservations")
.where("ordini", "<", 10).limit(5);
return itemsRef.get()
.then((querySnapshot) => {
return querySnapshot.docs.map(doc => doc.data());
})
.catch((error) => {
console.log("Error getting documents: ", error);
});
}
Then, in html page I have a button to return the items:
<ion-content>
<div class="flexbox-container" style="display:flex;">
<div *ngIf="item0" class="sidebar" style="flex:1;">
<video id="video1" height="320" width="240" controls>
<source src="{{item0?.downloadURL}}" type="video/mp4">
<source src="{{item0?.downloadURL}}" type="video/ogg">
</video>
</div>
<div *ngIf="item1" class="main" style="flex:1;">
<video id="video2" height="320" width="240" controls>
<source src="{{item1?.downloadURL}}" type="video/mp4">
<source src="{{item1?.downloadURL}}" type="video/ogg">
</video>
</div>
</div>
</ion-content>
<ion-button id="button1" (click)="returnItems()">Return</ion-button>
What am I doing wrong?
I've noticed that every time I switch from items to list detail page, using the ionViewWillEnter() method, and try to print something in console, the print is recalculated but the data remain the same, so the problem I think is in html page:
ionViewWillEnter should work. Try ionViewDidEnter.
Maybe is late for an answer in this question but i think will be useful for future users.
Related to OP question the mos efficient way is that using Events. It is something similar of use of custom events in javascript.
Using events you can do or refresh everything even in cached pages/components.
Below shows how you can subscribe a listener then call the event from everywhere, doing that listener to intercept the event you have raised.
Page that needs to be refreshed after back button is pressed
page.ts
constructor(
private events: Events
) {}
ngOnInit() {
this.events.subscribe('back_refresh', (data) => { /*Do your operations here as it's always called */ });
}
Page where back button is present
page.html
<ion-back-button (click)="this.goBack()"></ion-back-button>
page.ts
constructor(
private navController: NavController,
private events: Events
) {}
private goBack(): void{
this.navController.pop();
// also you can pass your data here
this.events.publish('back_refresh', null);
}
How do I Implement a Search Bar in the Ionic app to filter Firebase data? I want to implement a to filter data as user types in. I am not able to get it done. I have seen several tutorials but still unable to achieve them. Any help will be appreciated.
this is my list.page.html
<ion-searchbar (ionChange)="search($event.target.value)"></ion-searchbar>
<ion-list class="bg-transparent " lines="none" *ngFor="let user of usersArrayFiltered" color="none" >
<ion-item color="none"> <ion-card>
<ion-card-content>
<h2>{{user.name}}</h2>
<p>{{user.email}}</p>
<p>₹ {{user.mobile}}</p>
</ion-card-content>
</ion-card>
</ion-item>
</ion-list>
</div>
</ion-content>
this is my list.page.ts
export class HomePage implements OnInit {
UsersArray = [];
usersArrayFiltered =[];
constructor(
private apiService: UserService
) { }
ngOnInit() {
this.fetchBookings();
let bookingRes = this.apiService.getUserList();
bookingRes.snapshotChanges().subscribe(res => {
this.UsersArray = [];
res.forEach(item => {
let a = item.payload.toJSON();
a['$key'] = item.key;
this.UsersArray.push(a as User);
this.usersArrayFiltered = [...this.UsersArray];
})
})
}
search(query) {
if (!query) { // revert back to the original array if no query
this.usersArrayFiltered = [...this.UsersArray];
} else { // filter array by query
this.usersArrayFiltered = this.UsersArray.filter((user) => {
return (user.name.includes(query) || user.email.includes(query) || user.phone.includes(query));
})
}
}
fetchBookings() {
this.apiService.getUserList().valueChanges().subscribe(res => {
console.log('Fetched users list!')
})
}
}
Here's a basic example. I would have two arrays – the original array usersArray which gets left unfiltered, and a modifiable array usersArrayFiltered which gets filters applied to it. You will bind to the filtered array in your HTML.
Right after you populate your usersArray with data in your ngOnOnit hook, assign usersArrayFiltered as a copy of the original array.
// just populated usersArray
this.usersArrayFiltered = [...this.usersArray];
Now create a search method that takes in the search query as a parameter. If the query is an empty string, then re-assign usersArrayFiltered as a copy of the original usersArray. If it's not an empty string, then turn usersArrayFiltered into a filtered array of usersArray by only including objects that have values which contain the query string.
search(query) {
if (!query) { // revert back to the original array if no query
this.usersArrayFiltered = [...this.usersArray];
} else { // filter array by query
this.usersArrayFiltered = this.usersArray.filter((user) => {
return (user.name.includes(query) || user.email.includes(query) || user.phone.includes(query));
})
}
}
Listen to value changes on your <ion-searchbar> and pass the value of it to your search function.
<ion-searchbar (ionChange)="search($event.target.value)"></ion-searchbar>
Bind your *ngFor loop to the filtered array.
<ion-list *ngFor="let user of usersArrayFiltered">
...
</ion-list>
I'm looking for some example but cannot see anyone googling it, just what i want is to hardcode 2 or 3 words, thank you so much. Do i have to look for on ionic 3? or in angular2 better?
In your html file:
<ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
<ion-list *ngIf="isItemAvailable">
<ion-item *ngFor="let item of items">{{ item }}</ion-item>
</ion-list>
in your ts file:
// Declare the variable (in this case and initialize it with false)
isItemAvailable = false;
items = [];
initializeItems(){
this.items = ["Ram","gopi", "dravid"];
}
getItems(ev: any) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
const val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() !== '') {
this.isItemAvailable = true;
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
} else {
this.isItemAvailable = false;
}
}
Mohan Gopi's answer is complete, but in order to make use of the debounce attribute, you have to use the ionChange event instead of the ionInput event.
<ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
...
...
That way the event will trigger after the user stops typing (after 500 milliseconds have passed since his last key press), instead of whenever a key is pressed.
Just wanted to share something I tried myself. I have implemented the autocomplete from Angulars material design (https://material.angular.io/components/autocomplete/overview)
But it did not look exactly as the rest of the ionic input components. I also tried the ion-searchbar but I did not like the search input, I wanted a normal ion-input So I did this:
html:
<ion-list>
<ion-item>
<ion-label position="floating">Supplier*</ion-label>
<ion-input (ionChange)="onSearchChange($event)" [(ngModel)]="supplier"></ion-input>
</ion-item>
<ion-item *ngIf="resultsAvailable">
<ion-list style="width: 100%; max-height: 200px; overflow-y: scroll;">
<ion-item *ngFor="let result of results" (click)="supplierSelected(result)" button>
<ion-label>{{result}}</ion-label>
</ion-item>
</ion-list>
</ion-item>
</ion-list>
in component.ts:
resultsAvailable: boolean = false;
results: string[] = [];
ignoreNextChange: boolean = false;
onSearchChange(event: any) {
const substring = event.target.value;
if (this.ignoreNextChange) {
this.ignoreNextChange = false;
return;
}
this.dataService.getStrings(substring).subscribe((result) => {
this.results = result;
if (this.results.length > 0) {
this.resultsAvailable = true;
} else {
this.resultsAvailable = false;
}
});
}
supplierSelected(selected: string) :void {
this.supplier = selected;
this.results = [];
this.resultsAvailable = false;
this.ignoreNextChange = true;
}
Granted the question was about ion-searchbar but maybe somebody out there also wants to use a normal ion-input like me. There is no clear icon but I can live with that, or just add one next to the ion-input. Could be that there is a way to turn the ion-searchbar into a normal ion-input style? Can't find it though in the docs.
I'm connecting ionic application with MySql database using PHP, all functionalities are working fine but when i upload data in database it is taking atleast hour of time for data updation in ionic application, Please find sample code for the same:
I havent used any sessions and when loading component every time will fire request to fetch data from dabase using PHP, tried placing ngZone but still issue remains same.
this.zone.run(() => {
this.http
.get('http://localhost:8100/dbcon/retreive-monthcircular.php')
.subscribe((monthdata : any) =>
{
console.dir(monthdata);
this.loadData = false;
this.circularmonthdata = monthdata;
if (this.circularmonthdata == null) {
this.displayCircular = false;
} else {
this.displayCircular = true;
}
},
(error : any) =>
{
console.dir(error);
});
});
Ideally Application should dynamically update
Look at this example
HTML :
<ion-item>
<ion-label>Date</ion-label>
<ion-datetime displayFormat="DD/MM/YYYY" pickerFormat="DD/MM/YYYY" [(ngModel)]="myDate"></ion-datetime>
</ion-item>
<button ion-button block (click)="getData(myDate)">Get Data</button>
Bellow is your current data from array we created.
<ion-item *ngFor="let data of fetchedData">
Date: {{data.date}} - Description: {{data.description}}
</ion-item>
your TS:
fetchedData = [ // suppose your data looks like this
{
date: '20-02-1990',
description: 'this is First date'
},
{
date: '21-03-1991',
description: 'this is Second date'
}
]
getData(myDate){
this.headers = {'Content-Type': 'application/json'};
this.http.get('http://localhost:8100/dbcon/retreive-monthcircular.php', {headers: this.headers})
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.fetchedData = data.data; // update your variable it will update data on your view.
});
}
by clicking on this function will update your data at DOM. Or you should post your HTML and fetched Data from server.
I've created Rest API, connected to Ionic app successfully and displayed data.
home.html
<ion-content padding>
<ion-card *ngFor="let item of allProducts">
{{item.title}}
</ion-card>
</ion-content>
home.ts
ionViewWillEnter(){
this.productProvider.getProduct()
.subscribe(productList=> this.allProducts=productList);
}
API has example data like below, product titles like below:
abc
xyz
rmn
zxy
My question is:
In search bar, if I give abc and then enter, it should display that particular product.
How can I do this? I tried <ion-searchbar> but it is not working.
Could any one tell me how to do this? Or is there any tutorial for my case?
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
getItems(event) {
let search = event.target.value;
if (search && search.trim() != '') {
this.productProvider.getProduct(search).subscribe((products) => {
console.dir(products);
}, (err) => {
console.log(err);
});
}
}
You can use ionInput event to send search based api request