How to search based on Rest API data? - rest

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

Related

how to show the selected value in radio button as checked when opening the ion-lost again after selection in ionic

I have a field which opens a list having ion-radio.On selection of an option it shows the selected value as checked and when i open the list again, the checked value is not shown.
here is my code:
code to show the options in modal controller :
let modal = this.modalCtrl.create(ListComponent, { selectEmpType: type, selectValue: value, customiseColor: this.customiseColor , formMrType :formMrType, limitedRoleList : this.limitedRoleList, formType:this.formType,defaultOU1:this.defaultOus[0],defaultOU2:this.defaultOus[1],defaultOU3:this.defaultOus[2]});
modal.onDidDismiss(data => {
if (data.type == 'single') {
this.setEmpValue(data.data, name); //data.data is the value that is selected from the list
}
}
in listcomponent.html:
<div *ngIf= "formMrType =='employee'">
<ion-list radio-group [(ngModel)]="relationship">
<ion-item *ngFor="let option of inputDatas">
<ion-label>{{option.EMPFullName}}</ion-label>
<ion-radio [checked]="option.checked" value="{{option.EMPFullName}}"></ion-radio>
</ion-item>
</ion-list>
</div>
how to show the selected option as checked when opening the list for second time.
Preferably, you should be using ion-select for such functionality..
If you are using latest ionic versions ion-radio-group
But even in your case..you can try something like this...
<ion-radio [checked]="option.checked" value="{{option.EMPFullName}}" (ionBlur)="optionBlur(option)"></ion-radio>
optionBlur(option){
if(!option['checked']){
option['checked'] = true;
}
else{
option['checked'] = !option['checked']
}
}

Not able to show the image according to condition in Ionic

I am working in Ionic project and I am showing the user profile image in Ionic. When the user is login, the original profile image will show otherwise the demo image will show but the problem is that It is not showing the demo image when the user is not login.
This is my app.html:
<ion-col col-4>
<img class="imgsection12" src="{{this.userpimage ? 'assets/imgs/hipster-man.jpg' : 'http://beegoodhoney.in/uploads/user/'+this.userpimage}}" />
</ion-col>
In this html, I have used the condition that if the this.userpimage is set, it will show the original profile image otherwise it will show the demo image but the problem is that it is not showing=ng the demo image when the user is not login.
This is my app.component.ts:
userpimage;
this.storage.get("IMAGE2").then((val2) =>
{
if(val2)
{
this.userpimage = val2;
console.log(this.userpimage);
}
});
When I console the value, it is showing the image name.
Any help is much appreciated.
Try this instead
HTML:
<ion-col col-4>
<img class="imgsection12" [src]="profileImage" />
</ion-col>
Component.ts:
public profileImage = './assets/imgs/hipster-man.jpg';
userpimage;
this.storage.get("IMAGE2").then((val2) =>
{
if(val2)
{
this.userpimage = val2;
console.log(this.userpimage);
this.profileImage = `http://beegoodhoney.in/uploads/user/${this.userpimage}`;
}
});
That way later when you logout you can set the profileImage variable to something else if you want, like back to './assets/imgs/hipster-man.jpg'; for example.

Ionic list refresh after deleting an item

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

Ionic 3 Navigation New page hidden

I am using ionic 3.10.3 my root page is loginPage then after user validation its redirect to HomeViewPage by as bellow
this.nav.setRoot(HomeViewPage);
no problem to now but in the HomeViewPage If the user click add button it must be redirect to NewItemPage I tried to use
this.nav.setRoot(NewItemPage, {itemID: _id, isNew: _isNew});
and
this.nav.push(NewItemPage, {itemID: _id, isNew: _isNew});
bellow is the new function
newItem(){
this.events.publish('apps:viewItem', this.handlerService.getNewID(), "1");
}
and this is the code in app.component.ts the receive event
this.events.subscribe('apps:viewItem', (_id, _isNew) => {
this.menu.close();
this.rootPage = NewItemPage;
this.nav.setRoot(NewItemPage, {itemID: _id, isNew: _isNew}).then(()=>{
this.nav.popToRoot();
}).catch(err=>{
alert("NewItemPage Error : " + err.toString());
});
});
but still in the HomeViewPage even i clicked the button many times
but when I click back button it return to NewItemPage but now data exists.
Any help
The problem was in NewItemPage the I use a null object property
<ion-item>
<ion-label>Activity Type</ion-label>
<ion-select [(ngModel)]="handlerService.dataService.item.activityType">
<ion-option *ngFor="let g of handlerService.dataService.activityTypes" value="{{g.id}}">{{ g.name }}</ion-option>
</ion-select>
</ion-item>
handlerService.dataService.item is an object that must be initialized

Ionic Master Detail view with Firebase auto-generated child key returning JSON $value null

I am new to Ionic and Firebase. While fetching data for details view I am getting undefined value for $scope.program.
However, I have fetched the complete programs list in Master view. Clicking the list item from master view returns index (0, 1, 2, etc) of the list in console log but not the child key (which I was expecting)
During my research, I found out this question quite relevant to my problem, by Wes Haq. But while implementing the same, it has no change in the result. Please help.
From the above question by Wes Haq, I couldn't find the state provider details. I may be missing something there. Thanks in advance to all.
controllers.js
.controller('myServicesCtrl', ['$scope', '$state', '$stateParams', '$ionicActionSheet', 'AgencyProgService',
function ($scope, $state, $stateParams, $ionicActionSheet, AgencyProgService) {
//Only items relative to the logged/signed in Agency shall be pushed to the scope.items
$scope.programs = AgencyProgService.getPrograms();
}])
.controller('serviceDetailCtrl', ['$scope', '$stateParams', 'AgencyProgService',
function ($scope, $stateParams, AgencyProgService) {
AgencyProgService.getProgram($stateParams.index).then(function (program) {
$scope.program = program;
});
console.log("serviceDetailCtrl: scope.program is: " + $scope.program);
}])
service.js
.service('AgencyProgService', ['$q', '$firebaseArray', '$firebaseObject', 'AgencyDataService', function ($q, $firebaseArray, $firebaseObject, AgencyDataService) {
var ref = firebase.database().ref().child('programs/'); // this is a valid ref with https://my-demo.firebaseio.com/programs
var agencyIDfromPrograms = AgencyDataService.getAgencyUID();
var refFilter = ref.orderByChild("agencyID").equalTo(agencyIDfromPrograms);
return {
getPrograms: function () {
return $firebaseArray(refFilter);
},
getProgram: function (programId) {
console.log("getProgram: ID is: " + programId + "And refFilter to use is: " + ref);
var deferred = $q.defer();
var programRef = ref.child(programId); // here programId should be the autogenerated child key from fire DB "programs"
var program = $firebaseObject(programRef);
deferred.resolve(program);
return deferred.promise;
}
}
}])
Views:
myServices.html
<ion-list id="myServices-list9">
<ion-item id="myServices-list-item11"
ng-repeat="item in programs" ui- sref="serviceDetail({index: $index})">
<div class="item-thumbnail-left">
<i class="icon"></i>
<h2>{{item.progName}} </h2>
<p>{{item.servType}} for: {{item.servHours}}</p>
<p>From: {{item.servStartDate}}</p>
</div>
</ion-item>
</ion-list>
serviceDetail.html
<div class="list card">
<div class="item item-avatar">
<img src="{{item.user.picture.thumbnail}} " />
<h1>{{program.servContact}}</h1>
<h2>{{program.$id}} {{program.progName}}</h2>
<p>{{item.servContact}} {{item.servStartDate}}</p>
</div>
<pre> {{program | json}} </pre>
From serviceDetail view, no data from program is visible, as you can see from the screen shot below. List card for serviceDetail. on clicking 2nd item on myServices, it shows this detail screen with $id as 1. Expected is the child key for programs:
Firebase data structure screenshot for child programs is as below,
Appreciate your suggestions.