How to add Social share to a post Ionic wordpress app - android

I have been trying to insert a share button for a post in my app that is able to use the default apps installed in the android phone and can not seem to find a way through.
This is how my post.ts file looks like
import { Component } from '#angular/core';
import { NavParams, NavController, AlertController } from 'ionic-angular';
.
.
import { SocialSharing } from '#ionic-native/social-sharing';
/**
* Generated class for the PostPage page.
*/
#Component({
selector: 'page-post',
templateUrl: 'post.html'
})
export class PostPage {
post: any;
user: string;
comments: Array<any> = new Array<any>();
categories: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
public alertCtrl: AlertController,
private socialSharing: SocialSharing
) {
}
ionViewWillEnter(){
this.morePagesAvailable = true;
this.post = this.navParams.get('item');
Observable.forkJoin(
this.getAuthorData(),
this.getCategories(),
this.getComments())
.subscribe(data => {
this.user = data[0].name;
this.categories = data[1];
this.comments = data[2];
});
}
getAuthorData(){
return this.wordpressService.getAuthor(this.post.author);
}
getCategories(){
return this.wordpressService.getPostCategories(this.post);
}
getComments(){
return this.wordpressService.getComments(this.post.id);
}
loadMoreComments(infiniteScroll) {
let page = (this.comments.length/10) + 1;
this.wordpressService.getComments(this.post.id, page)
.subscribe(data => {
for(let item of data){
this.comments.push(item);
}
infiniteScroll.complete();
}, err => {
console.log(err);
this.morePagesAvailable = false;
})
}
goToCategoryPosts(categoryId, categoryTitle){
this.navCtrl.push(HomePage, {
id: categoryId,
title: categoryTitle
})
}
// Social sharing function is here
sharePost() {
this.socialSharing.share("Post Excerpt", "Post Title", "Post Image URL", "Post URL")
.then(() => {
console.log("sharePost: Success");
}).catch(() => {
console.error("sharePost: failed");
});
}
}
Problem
How do insert the post title, post url post image (REST API - JSON) into this.socialSharing.share("Post Excerpt", "Post Title", "Post Image URL", "Post URL")
so that the share button can look more like this
<button ion-fab class="btn share" mini (click)="sharePost()"></button>
EDIT
I have managed to make it work using
sharePost() {
this.socialSharing.share(this.post.excerpt.rendered, this.post.title.rendered, this.post.images.large, this.post.link)
.then(() => {
console.log("sharePost: Success");
}).catch(() => {
console.error("sharePost: failed");
});
}
However when i share like using gmail, the html special characters display
e.g title shows: catering & Cleaning Services
Excerpt shows: <p>Some text[…]</p>
How do i get rid of those html characters and just show some clean text.?
Thank you

One way i removed html tag from my wordpress post was to create a pipe and i pass the excerpt through the pipe before it gets rendered to the view
Pipe.ts was like so
import { Pipe, PipeTransform } from '#angular/core';
/**
* Generated class for the RemovehtmltagsPipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/
#Pipe({
name: 'RemovehtmltagsPipe',
})
export class RemovehtmltagsPipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: string) {
if (value) {
let result = value.replace(/<\/?[^>]+>/gi, "");
return result;
}
else {
}
}
}
Then i added the pipe as export in my component's module.ts
details.module.ts was like so
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { DetailsPage } from './details';
import { RemovehtmltagsPipe } from
'../../pipes/removehtmltags/removehtmltags';
#NgModule({
declarations: [
DetailsPage,
],
imports: [
IonicPageModule.forChild(DetailsPage),
],
exports: [RemovehtmltagsPipe],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class DetailsPageModule {}
Finally used the pipe inside my html code
details.html
<ion-row class="white-bg" padding>
<ion-col>
<h1 class="title">{{article.title.rendered | RemovehtmltagsPipe}}</h1>
<p class="date">Published: {{article.modified.split('T')[0]}} {{article.modified.split('T')[1]}}</p>
</ion-col>
</ion-row>
This should get rid of any html tags in your post.Hope this helps

Related

how to launch camera in an ionic app

I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}

Ionic httpClient response use toast

i send login data to service, after get response in login.ts toast is not difined, how to resolve this ?
i try my toast function in another function withot condition in service its work
this my function for load service login.ts:
import { Component, OnInit } from '#angular/core';
import { NavController, MenuController, PopoverController } from "ionic-angular";
import { TabsInfluencerComponent } from '../../influencer/tabs/tabs';
import { RegisterComponent } from '../register/register';
import { ResetComponent } from '../reset/reset';
import { OfferComponent } from '../../advertiser/offer/offer';
import { ngForm } from '#angular/forms';
import { AuthService } from '../../../services/auth';
import { ToastController } from 'ionic-angular';
#Component({
templateUrl: 'login.component.html',
})
export class LoginComponent implements OnInit {
constructor(
public nav:NavController,
public menu:MenuController,
public popover: PopoverController,
private AuthService : AuthService,
private toastCtrl: ToastController) {
}
responseData : any;
public isChoose: boolean = false;
public isshowP: boolean = false;
//login and get data in service
login(form: ngForm){
this.AuthService.login(form.value.email, form.value.password)
.then(function(data) {
if(data.success == true){
localStorage.setItem('userToken',data.token);
localStorage.setItem('userData',JSON.stringify(data.user));
}else{
let toast = this.toastCtrl.create({
message: data.error,
duration: 3000
});
toast.present();
}
})
.catch(function(error) {
console.log(error);
})
}
}
this my service auth.ts:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators'
#Injectable()
export class AuthService {
private loginUrl : string = 'http://localhost:8000/api/login';
data : any;
constructor(private http: HttpClient){}
//function for login
login(email : string, password :string){
const body = {email : email, password : password};
return new Promise(resolve => {
this.http.post(this.loginUrl, body)
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
register(email : string, password :string){
}
}
after run i have error like this :
TypeError: Cannot read property 'toastCtrl' of undefined
In this case it is a problem with your this reference in your login.ts.
.then(function(data) {
...
let toast = this.toastCtrl.create({
message: data.error,
duration: 3000
});
...
})
The this is referring the anonymous function in your then block, but you want to refer back to your LoginComponent class.
How to solve this?
You could use arrow functions, that are really popular right now.
.then((data) => {
...
let toast = this.toastCtrl.create({
message: data.error,
duration: 3000
});
...
})

Where does my image been stored in Ionic application?

I am very new to Ionic and Cordova, for the last couple of days I am trying to download an image that I have upload in firebase storage. I want to transfer the image and store it in my mobile device through my mobile application. I have installed all the plugins needed to do that. I have created two buttons. The first button is to display the image in my application and the second button is to download the image in my device. The source code for that is in my storage.html
<ion-header>
<ion-navbar>
<ion-title>storage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-button (click)="display()">Display</button>
<button ion-button (click)="download()">Download</button>
<img src="{{imgsource}}">
</ion-content>
The functionality is in my storage.ts
import { Component, NgZone } from '#angular/core';
import { NavController, Platform, AlertController } from 'ionic-angular';
//import {File,Transfer} from 'ionic-native';
import {FileTransferObject } from '#ionic-native/file-transfer';
import {TransferObject} from '#ionic-native/transfer';
import {Transfer} from '#ionic-native/transfer';
import {File} from '#ionic-native/file';
import firebase from 'firebase';
declare var cordova: any;
#Component({
selector: 'storage-home',
templateUrl: 'storage.html',
providers: [Transfer, TransferObject, File]
})
export class StoragePage {
storageDirectory: string = '';
fileTransfer: FileTransferObject;
nativepath: any;
firestore = firebase.storage();
imgsource: any;
constructor(public navCtrl: NavController, public platform: Platform, public alertCtrl: AlertController, public zone: NgZone) {
this.platform.ready().then(() => {
// make sure this is on a device, not an emulation (e.g. chrome tools device mode)
if(!this.platform.is('cordova')) {
return false;
}
if (this.platform.is('ios')) {
this.storageDirectory = cordova.file.documentsDirectory;
}
else if(this.platform.is('android')) {
this.storageDirectory = cordova.file.dataDirectory;
}
else {
// exit otherwise, but you could add further types here e.g. Windows
return false;
}
});
}
display() {
this.firestore.ref().child('image.jpg').getDownloadURL().then((url) => {
this.zone.run(() => {
this.imgsource = url;
this.fileTransfer.download(url,'image.jpg').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
})
})
}
downlad() {
this.firestore.ref().child('image.jpg').getDownloadURL().then((url) => {
this.zone.run(() => {
this.imgsource = url;
this.fileTransfer.download(url,cordova.file.dataDirectory +'image.jpg').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
})
})
}
}
The display button works perfectly as I can see my image when I install the application on my device. The problem though is with the download button as nothing is happening and I don’t know if it’s working as I can’t find my image anywhere in my device. Can anyone please guide me?
Thanks in regards
It looks like you may have a typo on your download function name. In the HTML module you refer to download() and in your code your function is labeled as downlad.

Angular 2 broadcasting events to notify other components

So I'm actually loosing my mind. I'm new to Angular 2 and I'm trying to understand how to let sibling child components comunicate between each other.
I have n child components that can play an Audio file.
The goal is to stop playing component if someone is started.
E.G. : component 1 is played, I play start on component 2, component 1 is stopped, component 2 is played.
I tried with shared service with no luck and also trying with EventEmitter comunicating from child to parent but it is not working.
I cannot figure out how to notify all components at once.
RegistrationComponent ( child )
import {Component, Input, Output, EventEmitter} from '#angular/core';
import {Path} from "./data-model";
import {MediaPlugin} from '#ionic-native/media';
import {Platform} from 'ionic-angular';
import {SocialSharing} from '#ionic-native/social-sharing';
import {RegistrationService} from './registration.service';
#Component({
selector: 'registration',
template: `
<div class="reg__name">{{ url.name }}</div>
<button ion-button color="secondary" item-right clear large (click)="toggle(url.path);">
<ion-icon [name]="playing ? 'md-square' : 'md-play'"></ion-icon>
</button>`,
providers: [
MediaPlugin,
SocialSharing,
RegistrationService
]
})
export class RegistrationComponent {
#Input() url: Path;
#Input() someonePlaying: boolean = false;
#Output() onPlayed = new EventEmitter<boolean>();
playing: boolean = false;
mediaContainer: any;
path: string;
constructor(private media: MediaPlugin,
private platform: Platform,
private socialSharing: SocialSharing,
private service: RegistrationService) {
this.path = "assets/audio";
// service.playing.subscribe(val => this.onSomeonePlaying(val));
}
ngOnChanges() {
console.log(this.someonePlaying);
}
toggle(filename) {
this.playing
? this.stop()
: this.play(filename)
}
play(fileName) {
const mp3URL = this.getMediaURL(`${this.path}/${fileName}`);
this.mediaContainer = this.media.create(mp3URL);
this.mediaContainer.play();
this.playing = true;
this.onPlayed.emit(true);
}
stop() {
this.mediaContainer.stop();
this.playing = false;
// this.service.stop();
}
share() {
this.socialSharing.shareViaWhatsApp("Condividi su Whatsapp", "", "");
}
onSomeonePlaying(val: boolean) {
console.log(val);
}
getMediaURL(s) {
let isAndroid = this.platform.is("android");
return isAndroid ? `/android_asset/www/${s}` : s;
}
}
Portion of home.html that prints the components
<ion-item *ngFor="let url of currentUrls">
<registration (onPlayed)="onPlayed($event)"
[(someonePlaying)] = "globalPlaying"
[url]="url"></registration>
</ion-item>
*home.ts**
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {Registrations, Registration} from './data-model';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
path: string;
urls: Array<any>;
currentUrls: Array<{name: string, path: string}>;
globalPlaying: boolean = false;
constructor(public navCtrl: NavController) {
this.path = "assets/audio";
this.urls = Registrations;
this.currentUrls = [];
for (let i = 0; i < this.urls.length; i++) {
this.currentUrls = this.currentUrls.concat(this.urls[i]["paths"]);
}
}
onChange(key) {
this.currentUrls = this.filter(key);
}
onPlayed(val){
console.log("global playing", val);
this.globalPlaying = true;
}
filter(key) {
if (!key || key === "all")
return this.findAll(this.urls);
return this.findWhere(this.urls, key)["paths"];
}
findAll(collection) {
let array = [];
for (let i = 0; i < collection.length; i++) {
array = array.concat(collection[i]["paths"]);
}
return array;
}
findWhere(collection, key) {
for (let i = 0; i < collection.length; i++) {
if (collection[i]["id"] === key)
return collection[i];
}
}
}
You should subscribe to EventEmitter to catch the events. You need a service with an EventEmitter:
#Injectable()
export class MyService
{
myEventEmiter:EventEmitter<void> = new EventEmitter<void>();
}
Then inject service into your component and subscribe to it to catch the events:
contsruct(protected myService:MyService){}
ngOnInit()
{
this.myService.subscribe(
() => { //An event occurs }
);
}
At the other hand in another component you should emit the EventEmitter to create new event:
this.myService.emit();
I used an event to notify other instances to hide, of my date-picker component.
Please follow
event-broadcasting-in-angular-2
You have to create a broadcaster and messageEvent.

Ionic 2 local storage read issue when build with '--prod'

I am building an app that does an auto login for the user when app starts if it was closed without logging out the last time. This is done by setting a local storage value at successful login and reading it in the constructor of the landing page, which is the login page.
I used ionic build android -release to build and app worked fine. But it takes about 10 sec to load. After some search, I found building the app with --prod can reduce the load time and it did reduce my app load time to 4 sec.
But now the app can't read local storage value at the start. No errors., but, it just returns the value as null. In other pages the app can read the local storage though. Looks like some needed components are not fully loaded, when the app reaches the landing page. But, by the time user logins manually those are loaded. How do I implement an auto login while reducing the load time?
import { Component } from '#angular/core';
import { NavController, MenuController, NavParams } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { Global } from '../../providers/global';
import { HomePage } from '../home/home';
import { Storage } from '#ionic/storage';
import { Network } from 'ionic-native';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loginUserID: string = '';
loginUserPass: string = '';
showLogin = false;
constructor(private menu: MenuController, private navCtrl: NavController, private auth: AuthService, private global: Global, private storage: Storage, private navParams: NavParams) {
this.storage.get('user_id').then((value) => {
if(this.navParams.get('showLogin')){
this.showLogin = true;
}
else{
if(value && value != null){
this.navCtrl.setRoot(HomePage);
}
else{
this.showLogin = true;
}
}
});
if(this.global.hardwareBackAction != null){
this.global.hardwareBackAction();
}
}
ionViewDidLoad() {
this.menu.swipeEnable(false, 'side-menu');
}
public login() {
if (Network.type == 'none') {
this.global.showAlert('Information', 'No internet access');
}
else {
this.global.showLoading();
this.auth.login(this.loginUserID, this.loginUserPass).subscribe(allowed => {
this.global.loading.dismiss();
if (allowed) {
setTimeout(() => {
this.storage.set('user_id', this.loginUserID);
this.navCtrl.setRoot(HomePage);
});
}
},
error => {
this.showError(error);
});
}
}
showError(text) {
setTimeout(() => {
this.global.loading.dismiss();
});
this.global.showAlert('Error', text);
}
}

Categories

Resources