Search code examples
angularcordovaionic-frameworkionic-native

ionic contacts get phone number


I have the following code:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Screenshot } from '@ionic-native/screenshot';
import { AlertController, ToastController } from 'ionic-angular';
import { Contacts } from "@ionic-native/contacts";
import { SMS } from "@ionic-native/sms";


@Component({
  selector: 'page-item-details',
  templateUrl: 'item-details.html'
})
export class ItemDetailsPage {
  selectedItem: any;
  screen: any;
  state: boolean = false;
  alert:AlertController;
  contactList: Contacts;
  message: SMS;

  constructor(private toastCtrl: ToastController, private sms: SMS, public alertCtrl: AlertController, private contacts: Contacts ,public navCtrl: NavController, public navParams: NavParams,private screenshot: Screenshot) {
    this.selectedItem = navParams.get('data');
    this.alert = alertCtrl;
    this.message = sms;
    this.contactList = contacts;
  }


  sendToContact() {
    if (this.selectedItem['links'][0]['href'] != null) {
      this.contactList.pickContact().then((contact) => {

        this.message.send('phonexxxxxx',
          this.selectedItem['links'][0]['href'] +" Hey! Checkout this cool product listing on xxxx.com"
          ,).then((result) => {
          let successToast = this.toastCtrl.create({
            message: "Text message sent successfully! :)",
            duration: 3000
          })
          successToast.present();
        }, (error) => {
          let errorToast = this.toastCtrl.create({
            message: "Text message not sent. :(",
            duration: 3000
          })
          errorToast.present();
        });
      },()=>{
        console.log("rejected");
      });
    }
  }

}

How do I grab a users phone number? I am able to get to the contacts list and return a selected contact. How do I navigate within that object? I believe it gives me a list of phone numbers. I just want one or maybe have the user choose if multiple.


Solution

  • After getting the contact object, use contact.phoneNumbers[0].value for grabbing the first phone number.