I am doing notifications in ionic 2 i have taken one toggle button and wrote the get and post call for that one.
below is my html code.
<ion-header>
<ion-navbar>
<ion-title>Notifications</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-item no-lines (click)="Update()">
<ion-label> Notification</ion-label>
<ion-toggle checked={{notify}} ></ion-toggle>
</ion-item>
</ion-content>
below is my ts file..
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Logger } from '../../providers/logger/logger';
import { Rest } from '../../providers/network/rest';
/*
Generated class for the Notifications page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-notifications',
templateUrl: 'notifications.html'
})
export class NotificationsPage {
public noteValue;
public notify : boolean;
NotificationsArray=[];
constructor(public navCtrl: NavController,
public logger: Logger,
public rest: Rest){
}
ionViewDidLoad() {
this.rest.get('/getNotification')
.subscribe((result)=>
{
console.log("checking getNotification"+JSON.stringify(result));
//this.logger.debug(["getNotification"][0]["newsletter"]);
if(result.status == '1'){
if(result.notify == '1'){
this.notify=true;
console.log("success of getNotification");
//this.NotificationsArray=result.data;
}
else{
this.notify=false;
console.log("error of getNotification");
}
}
})
}
Update(){
let setNotificationObj = {
newsletter:this.notify
}
this.notify = !this.notify;
console.log("cheking setNotificationObj " + JSON.stringify(setNotificationObj));
this.rest.post('/setNotification',setNotificationObj)
.subscribe((result)=>
{
console.log("checking data of success " +JSON.stringify(result));
if(result.status == '1'){
}
else{
console.log("error");
}
});
}
}
my get call is working but when i am off&on the toggle button its getting json at position 0 error. please check my post call..
Related
I'm trying to get data from a api but I cannot print the values in the app. doesn't read the json correctly. not sure what I did wrong..any help for would be helpful. I need to be able to parse down in the json to get the strat_name
this is my code
home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { RestApiProvider } from '../../providers/restapi/restapi';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
names: string[];
errorMessage: string;
descending: boolean = false;
order: number;
column: string = 'name';
constructor(public navCtrl: NavController, public rest: RestApiProvider) { }
ionViewDidLoad() {
this.getNames();
}
getNames() {
this.rest.getNames()
.subscribe(
names => this.names = names,
error => this.errorMessage = <any>error
);
}
sort() {
this.descending = !this.descending;
this.order = this.descending ? 1 : -1;
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Name List
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<button ion-button type="button" (click)="sort()">Sort</button>
<h1>{{names | json}}</h1>
<ion-item *ngFor="let c of names | search : terms | sort: {property: column, order: order}">
<h2>{{c.strat_name}}</h2>
</ion-item>
</ion-content>
restapi:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
#Injectable()
export class RestApiProvider {
private apiUrl = 'https://macrostrat.org/api/v2/defs/strat_names?all';
constructor(public http: HttpClient) {
console.log(this.apiUrl);
}
getNames(): Observable<string[]> {
return this.http.get(this.apiUrl).pipe(
map(this.extractData),
catchError(this.handleError)
);
}
private extractData(res: Response) {
let body = res;
return body || {};
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
not sure what I did wrong..any help for would be helpful. I need to be able to parse down in the json to get the strat_names.
first, it loads the json
once I click on search
There are multiple issue in your code
1.Your data is coming like { success : { data : array} } so to access data you need to do below
private extractData(res: any) {
if (res && res.success && res.success.data) {
return res.success.data;
}
return [];
}
2.In your html you need to access the properties like this
<ion-item *ngFor="let n of names">
<h2>{{n?.strat_name}}</h2>
</ion-item>
3.Your data is too much and cause a lot of delays to show the data
After all of that fixes it will look like below
https://stackblitz.com/edit/ionic-jb6ni9
when I retrieve data from a json file, in the *ngFor displays all the values in the popover, but I need a specific popover to display based only on the data for selected/clicked weapon. Here is my code any help would be greatly appreciated. Thank you again for your help
Home
import { Component } from '#angular/core';
import { NavController, ViewController, PopoverController, Events} from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
import { PopupPage } from './../../pages/popup/popup';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weapons: any;
errorMessage: string;
constructor(public navCtrl: NavController, public rest: RestProvider,
public popoverCtrl: PopoverController) {
}
ionViewDidLoad() {
this.getweapons();
}
getweapons() {
this.rest.getweapons()
.subscribe(
weapons => this.weapons = weapons,
error => this.errorMessage = <any>error);
}
presentPopover(myEvent)
{
let popover = this.popoverCtrl.create(PopupPage);
popover.present({
ev: myEvent
});
}
}
home.html
<ion-content>
<ion-searchbar [(ngModel)]="terms"></ion-searchbar>
<ion-item>
</ion-item>
<ion-list>
<button ion-item (click)="presentPopover($event)">
<ion-item *ngFor="let c of weapons?.weapon_category?.weapons | search : terms">
<h2>{{c.name}}</h2>
</ion-item>
</button>
</ion-list>
</ion-content>
popup.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController, Events} from 'ionic-angular';
import { RestProvider } from './../../providers/rest/rest';
import { HomePage } from './../../pages/home/home';
/**
* Generated class for the PopupPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-popup',
templateUrl: 'popup.html',
})
export class PopupPage {
rangeSettings = 20;
weapons: any;
errorMessage: string;
constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public rest: RestProvider) {
alert('inside the popup');
}
close() {
this.viewCtrl.dismiss();
}
getweapons() {
this.rest.getweapons()
.subscribe(
weapons => this.weapons = weapons,
error => this.errorMessage = <any>error);
}
ionViewDidLoad() {
this.getweapons();
}
}
popup.html
<ion-header>
<ion-navbar>
<ion-title>popup</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let c of weapons?.weapon_category?.weapons">
<h2>{{c.damage.base}}</h2>
<h2>{{c.damage.chest0}}</h2>
<h2>{{c.damage.chest1}}</h2>
<h2>{{c.damage.chest2}}</h2>
<h2>{{c.damage.chest3}}</h2>
<h2>{{c.damage.head1}}</h2>
<h2>{{c.damage.head2}}</h2>
<h2>{{c.damage.head3}}</h2>
</ion-item>
<ion-item>
<ion-range min="0" max="80" [(ngModel)]="rangeSettings" color="danger" pin="true" snaps="true" disabled=true></ion-range>
</ion-item>
</ion-list>
</ion-content>
Popover doesn't need to hit the REST call again. You can pass the chosen weapon to the popover as a parameter.
Change your function to accept a weapon (make sure you change the code in the HTML too)
presentPopover(myEvent, weapon)
And send it to the popover controller this way:
this.popoverCtrl.create(PopupPage, weapon);
Now in your popup.ts, decleare a weapon object in your class,
weapon : any;
and grab the weapon from the navParams in your constructor
this.weapon = this.navParams.data;
Change your <ion-item> in popup.html to display the selected one.
<ion-item>
{{weapon.damage.base}}
...
</ion-item>
Somebody please help me. I am trying to filter a JSON data but it does not working and also don't show an error.
i have read the ionic Documentation, but it just work for an array data.
this is my ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
//untuk membaca file json
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
//navigasi ke tampilPage
import { TampilPage } from '../tampil/tampil';
//panggil provider
import { AlQuranProvider } from '../../providers/al-quran/al-quran';
#Component({
selector: 'page-al-quran',
templateUrl: 'al-quran.html',
})
export class AlQuranPage {
searchQuery: string = '';
public alquranTerfilter: string[];
constructor(
private quranProvider: AlQuranProvider,
private http: Http,
public navCtrl: NavController,
public navParams: NavParams) {
}
ionViewDidLoad(){
this.quranInitializeItems();
}
quranInitializeItems(){
this.quranProvider.getQuran().subscribe(
(respon) => {
//this.alquran = respon;
this.alquranTerfilter = respon;
});
}
getItems(ev: any) {
// Reset items back to all of the items
this.quranInitializeItems();
// set val to the value of the searchbar
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
}
tampilkan(item){
this.navCtrl.push(TampilPage, {item: item});
}
}
//this.alquran = respon;
/*
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
*/
<!--
Generated template for the AlQuranPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>AlQuran</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of alquranTerfilter" (click)="tampilkan(item)">
<h2>{{item.judul}}</h2>
<h4>{{item.riwayat}}</h4>
<ion-icon name="arrow-forward" item-end></ion-icon>
</ion-item>
</ion-list>
</ion-content>
and this the provider
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the AlQuranProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class AlQuranProvider {
// public alquran: string[];
//public alquranTerfilter: string[];
constructor(public http: HttpClient, private httpnonclient: Http) {
}
getQuran(){
return this.httpnonclient.get('./assets/nash/tbQuran.json')
.map(respon => respon.json());
}
}
the filter doesn't working and doesn't showing any error.
sorry for my bad english.
I guess it's a search function right ? Try this
getItems(ev: any) {
this.quranInitializeItems();
var val = ev.target.value;
if (val && val.trim()) {
this.alquranTerfilter = this.alquranTerfilter.filter(
item => item.toString().toLowerCase().includes(val.toString().toLowerCase())
)
} else {
return [];
}
}
I didn't get your filter logic, and you forgot to return something in case your query is empty.
Hello guys this may be dumb question but am new for ionic development , am facing problem while trying to display values from jsonobject,now let me explain in detail am fetching jsonobject from webservice and need to display it and i have successfully fetched the value from service but couldn't be able to display it while am trying am getting Cannot ready property 'StatusName 'undefined now let me post what i have tried so far :
This is my json getting from service:
{
"StatusName": "Open",
"ApprovalStatusName": "Awaiting Approval",
"CreatedByName": "Mark (Marx)",
"LastModifiedByName": "Mark (Marx)",
"ContractID": 20,
"ContractCode": "PIL",
}
And this is the typescript page:
export class ContractApprovalViewPage {
private contracts :any;
private contracttype:any;
private results:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public contractApprovalViewService:ContractApprovalViewService ) {
this.contracts=this.navParams.get('result');
this.getContractApprovalView(this.contracts);
}
getContractApprovalView(contracttype){
this.contractApprovalViewService.getContractApproval(contracttype).then(data => {
//console.log(data);
this.results=data;
console.log(this.results);
console.log(this.results.CustomerName);
});
}
}
This is my service Page:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Events } from 'ionic-angular';
import 'rxjs/add/operator/map';
#Injectable()
export class ContractApprovalViewService {
private _result;
constructor(public http: Http, public events: Events) { }
getContractApproval(contracttype:any) {
return new Promise(resolve => {
this.http.get('http://172.16.6.187/sf/api/cnrt/getContractapprovalview/'+ contracttype.Column0 +'/C').subscribe(
data => {
// console.log('http://xxxx/xx/xx/'+ contracttype.Column0 +'/C');
this._result = data;
resolve(JSON.parse(this._result._body));
},
err => {
this._result = err;
// this.events.publish("message:error", JSON.parse(this._result._body));
}
);
});
}
}
This is my html Page:
<ion-header>
<ion-navbar>
<ion-title>Approval</ion-title>
</ion-navbar>
</ion-header>
<ion-content >
<ion-list no-padding>
<ion-card>
<ion-item >
{{results.StatusName}}
</ion-item>
</ion-card>
</ion-list>
</ion-content>
Don't know where am making mistake how someone teach me where am wrong, Thanks in advance !
First declare variable above constructor
statusName:string;
then in below function
getContractApprovalView(contracttype){
this.contractApprovalViewService.getContractApproval(contracttype).then(data => {
//console.log(data);
this.results=data;
console.log(this.results);
this.statusName = this.results.statusName;
//this.results.statusName status name key should match the response you are getting.
console.log(this.results.CustomerName);
});
}
}
now in html
just print status name
as you are not passing array so dont use results.statusname
<ion-content >
<ion-list no-padding>
<ion-card>
<ion-item >
{{statusName}}
</ion-item>
</ion-card>
</ion-list>
</ion-content>
Is there any way to send data {{error.value}} to another page using a method?
This is my code
<ion-row *ngFor="let errors of adp_principal_menuRS">
<ion-col class="info-col" col-4>
<button ion-button color="primary" small (click)="goToErrors(errors.event)">
{{errors.event}}
</button>
</ion-col>
</ion-row>
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
});
}
I want to send the {{errors.event}} value to another page in the goToErrors() method.
Thanks!
EDIT: I just achieve what I want. I edited the code
Data can be shared using BehaviorSubject between components via service.
Here is an example:
// service.ts
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class ShareService {
private errorSource = new BehaviorSubject<any>(null);
error$ = this.errorSource.asObservable();
setError(error: any){
this.errorSource.next(error);
}
Set the error event in parent component using setError method and subscribe the error in error component.
// error component.ts
constructor(share: ShareService) {
share.error$.subscribe(Err => this.error = Err);
Why don't you send the value using a navParam?
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
errorEvent: menu // <------------------------- Add this line
});
}
And in your AdpDetailPage:
export class AdpDetailPage{
constructor(public navParams: NavParams){
errorEvent = this.navParams.get('errorEvent');
console.log("errorEvent= ", errorEvent);
}
}
Use event emittor.
//Home component.ts import { Events } from 'ionic-angular'; constructor(public events: Events) {} directioChange(user) {this.events.publish('directiochanged', 'true');} //App.component.ts constructor(public events: Events) { events.subscribe('directiochanged', (direction) => { this.isRtl = direction;console.log(direction);});}
I generated a Plunker that hopefully matches with what you are trying to do.
https://plnkr.co/edit/MNqpIqJjp5FN30bJd0RB?p=preview
Service
import { Injectable } from '#angular/core';
#Injectable()
export class ErrorService {
errorInfo: string;
}
Component
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<button (click)="goToErrors()">{{errors.event}} </button>
<router-outlet></router-outlet>
</div>
`,
})
export class App {
name:string;
errors = { event: 'Test Error', otherInfo: 'Test Info' };
constructor(private errorService: ErrorService, private router: Router) {
this.name = `Angular! v${VERSION.full}`
}
goToErrors(): void {
// Code to navigate to the other component
this.errorService.errorInfo = this.errors.event;
this.router.navigate(['/a']);
}
}