Here is the code and I am receiving an error while passing this parameter from services.
export class CardsPage {
currentItems: Item[];
id: any;
getData: Object;
categories:any;
constructor(public navCtrl: NavController, public api:Api, navParams:
NavParams, items: Items, public http: HttpClient) {
this.id = navParams.get('idName') ||'';
console.log(this.id);
this.api.getCategoryPosts(this.id).subscribe(data=>{
console.log(data)
this.getData = data
},err=>{
console.log(err)
})
}
openItem(item){
this.navCtrl.push('ItemDetailPage', {
itemName: item
});
}
}
Here is my Ts file:
getCategoryPosts(category: any) {
return this.http.get(`${this.api_url}/posts?
categories=${category.id}`);
}
The error that i am receiving is Reference error: category is not defined Reference error. Category is not defined at new CardsPage
Hello just use ionViewWillEnter to get your parameter and no need to use OR operation while getting parameter so here is the solution.
ionViewWillEnter(){
this.id = navParams.get('idName')
}
then use ionViewDidEnter to fetch data through service.
ionViewDidEnter(){
this.api.getCategoryPosts(this.id).subscribe(data=>{
console.log(data)
this.getData = data
},err=>{
console.log(err)
})
}
Related
Please help how to pass param to another page in ionc 4?
As the push and navparam function seen not working anymore in ionic4.
https://medium.com/#muthudevendra/ionic-sharing-data-between-pages-8d0412cb8f58
Page1.ts
public country: string;
public email: string;
public password: string;
constructor(public nav: NavController) {}
goToAboutPage() {
let params: any = {
country: this.country,
email: this.email,
password: this.password
}
this.nav.navigateForward('/identity', { state: params }); // params to pass object/array
}
Page2.ts
constructor(public router: Router){
if (router.getCurrentNavigation().extras.state) {
const params = this.router.getCurrentNavigation().extras.state;
console.log(params.email)
console.log(params.password)
console.log(params.country)
}
}
in page.html use like this:
<ion-button routerLink="/yourAddress" [queryParams]="{ paramName : 'paramValue' }" ></ion-button>
in page.ts use like this:
import { NavController } from '#ionic/angular';
constructor(public navCtrl: NavController) {
this.navCtrl.navigateForward('/yourAddress?paramName=' + this.paramValue);
}
Read up on Activated route and NavigationExtras,
on page.ts have a function probably binded to a click event
goToNextpage() {
let navigationExtras : NavigationExtras = { state: { dataToBePassed:this.param }};
this.router.navigate(['/nextpage'], navigationExtras);
}
on nextpage.ts
import { ActivatedRoute, Router } from '#angular/router';
and do your dependency injection in the constructor like
constructor(
private route: ActivatedRoute,
private router: Router,
) {
this.route.queryParams.subscribe(params => {
if (this.router.getCurrentNavigation().extras.state) {
this.var = this.router.getCurrentNavigation().extras.state.dataToBePassed;
}
console.log(this.var); // will get you the data passed with key dataToBePassed
});
}
I am new to Ionic and trying to pass api from providers to application's ts page but I am getting an error, maybe I am passing the wrong id.
TS part:
export class CardsPage {
currentItems: Item[];
id: any;
getData: Object;
categories;
constructor(public navCtrl: NavController, public api:Api, navParams:
NavParams, items: Items, public http: HttpClient) {
this.id = navParams.get('idName') ||'';
console.log(this.id);
this.api.getCategoryPosts(this.id).subscribe(data=>{
console.log(data)
this.getData = data
},err=>{
console.log(err)
})
}
openItem(item){
this.navCtrl.push('ItemDetailPage', {
itemName: item
});
}
}
Api:
getCategoryPosts(category: any) {
return this.http.get(`${this.api_url}/posts?categories=${category.id}`);
}
I have posted the code part about my API and ts file now I want to pass data to next page using parameters. I wanted to know what should I pass in parameter to get data displayed in next page
According to your code, You are passing id directly to the Service's getCategoryPosts method. Therefore use category instead of category.id as below.
getCategoryPosts(category: any) {
return this.http.get(`${this.api_url}/posts?categories=${category}`);
}
It works but i anot getting the results it should sort. I am getting the same results regardless what i type in the searchbar
I want it to sort like autocomplete. to show results of what i type in the search bar
search.ts
#Component({ selector: "page-search", templateUrl: "search.html" })
export class SearchPage {
filter: string = '';
public userDetails: any;
public resposeData: any;
public dataSet: any;
public userSet: any;
public mediaSet: any;
public noRecords: boolean;
userPostData = {
uid: "",
token: "",
username: "",
bio: ""
};
constructor(
public common: Common,
public navCtrl: NavController,
public app: App,
public menu: MenuController,
public authService: AuthService,
public http: Http,
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen
) {
this.initializeItems();
this.mostmediaList();
}
initializeItems() {
return this.userPostData;
}
getItems(ev: any) {
this.initializeItems();
let val = ev.target.value;
if (val && val.trim() != '') {
this.authService.postData(this.userPostData, "userGroupSearch").then(
result => {
this.resposeData = result;
if (this.resposeData.allArtistsData) {
this.userSet = this.resposeData.allArtistsData;
console.log(this.userSet);
} else {
console.log("No access");
}
},
);
}
}
Since your code is wrapped into
if (this.resposeData.items) {
//some code
}
we know for sure that this.resposeData is not an array, since it has an items member (otherwise your code inside the if would not be executed and hence you would not get an error as in the case we have).
Since you call the parameter items at
this.userSet = this.resposeData.filter((items) => {
//some code
};
it is safe to assume that you wanted to filter this.resposeData.items instead of this.resposeData. So, you will need to make sure it is an array at the if
if (this.resposeData.items && Array.isArray(this.resposeData.items)) {
//some code
}
and filter this.resposeData.items instead of this.resposeData:
this.userSet = this.resposeData.items.filter((items) => {
//some code
};
I want to make a callback between two page.
In the page 1, i have this code:
DataInfo= [
{
Price: 0,
ClosePrice: 0,
UpdateTime:"",
DefaultPrice:0
}
]
GetClosePrice(i):number{
return DataInfo[i].ClosePrice;
}
i want to get the value of 'i' from the page 2, How can i load the function GetClosePrice() when the navcontroller return to the page 1 (this.navCtrl.pop())
SOURCE PAGE CLASS
this.navCtrl.push(Page,
{
data: this.data,
callback: this.getData
});
getData = data =>
{
return new Promise((resolve, reject) => {
for (let order of orders) {
this.data = data;
}
resolve();
});
};
TARGET PAGE CLASS
constructor(public navCtrl: NavController, public navParams: NavParams)
{
this.callback = this.navParams.get('callback');
this.data = this.navParams.get('data') || [];
}
sendData(event: any): void
{
this.callback(this.data).then( () => { this.navCtrl.pop() });
}
TARGET PAGE TEMPLATE
<button ion-button (click)="sendData($event)">
I answered similar question in Ionic forum. I just used Events listeners to achieve this behaviour.
MainPage-
import { NavController, Events } from 'ionic-angular';
import { OtherPage } from '../other/other';
export class MainPage{
constructor(private navCtrl: NavController,
private events: Events) { }
private pushOtherPage(){
this.events.subscribe('custom-user-events', (paramsVar) => {
// Do stuff with "paramsVar"
this.events.unsubscribe('custom-user-events'); // unsubscribe this event
})
this.navCtrl.push(OtherPage); // Push your "OtherPage"
}
}
OtherPage-
export class OtherPage {
// Under some function
this.navCtrl.pop().then(() => {
// Trigger custom event and pass data to be send back
this.events.publish('custom-user-events', myCustomParams);
});
}
Try this one - ionic2 pop with params
I am storing a user id in the storage and trying to get the stored id when the page is loaded.
Below is the code snippet
constructor(
private nav: NavController,
private auth: AuthService,
public clockservice: ClockService,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController,
public storage: Storage
) {
storage.get('name').then(val => {
this.username = val;
})
storage.get('id').then(val => {
this.userid = val;
console.log(this.userid);
})
}
ngOnInit() {
console.log("inside");
console.log(this.userid);
getStatus();
}
getStatus() {
this.showLoading();
this.clockservice.getinoutstatus(this.userid).subscribe(
result => {
if (result.success) {
// do something here
} else {
this.showError("API Error.");
}
this.loading.dismiss();
},
error => {
this.showError("API Error.");
}
);
}
The issue I face is the user id is not received in the ngOnInit event. The console log shows the ngOnInit is called even before the user id is received in the constructor.
console log:
inside
1
How to make sure that is ngOnInit even is called after all the get values received in the constructor?
The simplest solution would be to perform a Promise.all to wait for both storage values to be retrieved and to then call getStatus:
ngOnInit() {
Promise.all([
this.storage.get('name'),
this.storage.get('id')
])
.then(([name, id]) => {
this.username = name;
this.userid = id;
getStatus();
})
.catch(error => {
this.showError("Storage Error.");
});
}
Retrieving the storage values in the constructor would be okay, but - looking at the implementation - it seems likely that getStatus should not be called before ngOnInit. So move the storage calls and the promise chain into ngOnInit