I have two pages: tab2 and request. When I click the button on tab2 I want to send id data to the request page. I don't want to use local storage, i tried:
tab2.page.ts
clickFunc(){
this.router.navigate(['/request', id]);
}
request.page.ts
this.router.params.subscribe(params => {
console.log(params['id']); //it gives undefined.
});
When i receive the id values, request pg gives error.
Change the code in the request.page.ts file as mentioned below:
import { ActivatedRoute, Router } from '#angular/router';
constructor(private route: ActivatedRoute, private router: Router)
{
this.route.queryParams.subscribe(params => {
console.log(params['id']); // This will give you the id param's value
});
}
I hope it helps!
Related
We have used queryParams for angular projects. can we use queryParams in ionic project?
is there any side effect or security issues?
this.router.navigate(['your-page-name-here'], params);
You can use queryParams but it is not a recommended way because you are sending values as a part of router link. This also means that you are limited to strings only and objects need to be stringified (JSON.stringify()) and parsed each time you send data.
Better option is to use Extras State:
let navigationExtras: NavigationExtras = {
state: {
userData: this.user
}
};
this.router.navigate(['my-page'], navigationExtras);
In MyPage, get data from the State by injecting Router in constructor:
this.data = this.router.getCurrentNavigation().extras.state.userData;
Using Service: Also, you can create a service that has a getter and setter that you can use to save data in it before navigating and retrieve it after completing the navigation:
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class DataService {
private data = [];
constructor() { }
setData(id, data) {
this.data[id] = data;
}
getData(id) {
return this.data[id];
}
}
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}`);
}
I'm trying to work with one signal plugin in my ionic 2 app
I've installed Onesignal and it was working fine,but i don't know how to work with handleNotificationOpened function
there is no document at all (nothing was found)
this is my code:
this.oneSignal.handleNotificationReceived().subscribe((msg) => {
// o something when notification is received
});
but I have no idea how to use msg for getting data.
any help? link?
tank you
Here is how i redirect user to related page when app launch from notification.
app.component.ts
this.oneSignal.handleNotificationOpened().subscribe((data) => {
let payload = data; // getting id and action in additionalData.
this.redirectToPage(payload);
});
redirectToPage(data) {
let type
try {
type = data.notification.payload.additionalData.type;
} catch (e) {
console.warn(e);
}
switch (type) {
case 'Followers': {
this.navController.push(UserProfilePage, { userId: data.notification.payload.additionalData.uid });
break;
} case 'comment': {
this.navController.push(CommentsPage, { id: data.notification.payload.additionalData.pid })
break;
}
}
}
A better solution would be to reset the current nav stack and recreate it. Why?
Lets see this scenario:
TodosPage (rootPage) -> TodoPage (push) -> CommentsPage (push)
If you go directly to CommentsPage the "go back" button won't work as expected (its gone or redirect you to... who knows where :D).
So this is my proposal:
this.oneSignal.handleNotificationOpened().subscribe((data) => {
// Service to create new navigation stack
this.navigationService.createNav(data);
});
navigation.service.ts
import {Injectable} from '#angular/core';
import {App} from 'ionic-angular';
import {TodosPage} from '../pages/todos/todos';
import {TodoPage} from '../pages/todo/todo';
import {CommentsPage} from '../pages/comments/comments';
#Injectable()
export class NavigationService {
pagesToPush: Array<any>;
constructor(public app: App) {
}
// Function to create nav stack
createNav(data: any) {
this.pagesToPush = [];
// Customize for different push notifications
// Setting up navigation for new comments on TodoPage
if (data.notification.payload.additionalData.type === 'NEW_TODO_COMMENT') {
this.pagesToPush.push({
page: TodoPage,
params: {
todoId: data.notification.payload.additionalData.todoId
}
});
this.pagesToPush.push({
page: CommentsPage,
params: {
todoId: data.notification.payload.additionalData.todoId,
}
});
}
// We need to reset current stack
this.app.getRootNav().setRoot(TodosPage).then(() => {
// Inserts an array of components into the nav stack at the specified index
this.app.getRootNav().insertPages(this.app.getRootNav().length(), this.pagesToPush);
});
}
}
I hope it helps :)
I'm trying to return a single article from a Express API using Angular 2.
The Express app has this section of code for single get request:
router.get('/articles/:articleId', (req, res) => {
let articleId = req.params.articleId;
Article.findById(articleId, (err, article) => {
if(err) {
res.send(err);
} else {
res.json(article)
}
});
});
If I do console.log(article) it returns the whole JSON object in the terminal so it's working.
Next, the Article Service looks like this:
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ArticleService {
constructor( private http:Http ) {
console.log('Article service initialized...')
}
getArticles() {
}
getArticle(id) {
return this.http.get('http://localhost:3000/api/articles/'+id)
.map(res => res.json());
}
addArticle(newArticle){
}
deleteArticle(id){
return this.http.delete('http://localhost:3000/api/articles/'+id)
.map(res => res.json());
}
}
With the code above the deleteArticle(id) works.
And finally, the ArticleDetailComponent looks like this:
import { Component, OnInit } from '#angular/core';
import { ArticleService } from '../services/article.service';
import { Router, ActivatedRoute, Params } from '#angular/router';
import { ArticleComponent } from '../article/article.component'
import 'rxjs/add/operator/switchMap';
#Component({
selector: 'app-articledetail',
templateUrl: './articledetail.component.html',
styleUrls: ['./articledetail.component.css']
})
export class ArticleDetailComponent implements OnInit {
article: ArticleComponent;
title: string;
text: string;
constructor(
private router: Router,
private route: ActivatedRoute,
private articleService:ArticleService){
}
ngOnInit() {
var id = this.route.params.subscribe(params => {
var id = params['id'];
this.articleService.getArticle(id)
.subscribe(article => {this.article = article});
console.log(id) //returns article id correctly
});
}
}
The articledetail.component.html looks like this:
<div class="article-container">
<div class="col-md-12">
<h2>{{article.title}}</h2>
{{article.text}}
<br><br>
</div>
</div>
When I run the application I can get a list of articles and delete articles by Id, but I can't get single articles to be displayed in the ArticleDetailComponent.
If I do console.log(id) within the ArticleDetailComponent it shows the article id, but I can't get the JSON object in the response and show it in the HTML.
Could somebody please tell me what's missing?
Thanks
I actually see where your mistake is.. you need to initialize article to empty object, because angular is probably throwing errors in the console that it cannot find article.title. The error is probably: cannot find title of undefined. And when angular throws an error like that the whole app freezes, and you cannot do anything. So initialize article like this:
article: any = {} and it will work
The other alternative would be to use the "safe operator" (?) in the template like
{{article?.title}}. This prevents the error, so if article is undefined it wont throw the exception, but its not a good practice rly
The third alternative would be to add *ngIf on the HTML which is throwing errors if article is undefined. Like this:
<div class="article-container" *ngIf="article">
<div class="col-md-12">
<h2>{{article.title}}</h2>
{{article.text}}
<br><br>
</div>
</div>
at the moment iam implementing a signIn into my ionic 2 app.
I want to use ionic 2 native facebook and somehow save the data to my firebase app.
Is there any way to archive that?
One way is to create a new firebase auth user with the facebook email adress and some password hash, but maybe there is a better solution.
Here is what i got so far (i know, not much) :)
import {NavController, Loading, Platform, Storage, LocalStorage} from "ionic-angular";
import {OnInit, Inject, Component} from "#angular/core";
import {ForgotPasswordPage} from "../forgot-password/forgot-password";
import {SignUpPage} from "../sign-up/sign-up";
import {HomePage} from "../../home/home";
import * as firebase from 'firebase';
import {Facebook} from 'ionic-native';
/*
Generated class for the LoginPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
templateUrl: 'build/pages/auth/login/login.html',
})
export class LoginPage {
private local: any;
constructor(private navCtrl: NavController, private platform:Platform) {
this.local = new Storage(LocalStorage);
}
openForgotPasswordPage():void {
this.navCtrl.push(ForgotPasswordPage);
}
openSignUpPage():void {
this.navCtrl.push(SignUpPage);
}
login() {
firebase.auth().signInWithEmailAndPassword("test#test.com", "correcthorsebatterystaple").then(function (result) {
console.log("AUTH OK "+ result);
}, function (error) {
console.log("dawdaw");
});
}
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then(() => {
this.local.set('logged', true);
this.navCtrl.setRoot(HomePage);
}, (...args) => {
console.log(args);
})
} }
facebookLogin() {
Facebook.login(['public_profile', 'user_birthday']).then((result) => {
var creds = firebase.auth.FacebookAuthProvider.credential(result.access_token);
return firebase.auth().signInWithCredential(creds);
})
.then((_user) => {
console.log("_user:", _user);
})
.catch((_error) => {
console.error("Error:", _error);
});
}
see more info here - https://firebase.google.com/docs/auth/web/facebook-login#advanced-handle-the-sign-in-flow-manually
I have not tried this, so might not be 100% working, but try this Gist I found: https://gist.github.com/katowulf/de9ef6b04552091864fb807092764224