ContactsService Example

Here’s a minimal but complete example of a Lightning web component that uses ContactsService to select on-device contacts and then process the contact data in the component.

The component’s HTML template is minimal, with a button to start selecting contacts, and a place to display results.

1<!-- contactsServiceExample.html -->
2<template>
3
4    <!-- User interface control -->
5    <lightning-card title="ContactsService Example">
6        <div class="slds-var-m-around_medium">
7            <lightning-button
8                variant="brand"
9                label="Process Contacts"
10                onclick={handleImportContacts}
11                class="slds-var-m-left_x-small">
12            </lightning-button>
13        </div>
14    </lightning-card>
15
16    <!-- After contacts are selected, they're displayed here -->
17    <div class="slds-var-m-around_medium">
18        <p><b>Contacts Selected</b></p>
19        <p><lightning-formatted-text 
20            value={contactsResults}></lightning-formatted-text></p>
21        <ul class="slds-var-m-around_medium">
22            <template for:each={contacts} for:item="contact">
23                <li key={contact.Id}>
24                    {contact.name.givenName} {contact.name.familyName}
25                    <ul class="slds-var-m-around_medium">
26                        <template for:each={contact.phoneNumbers} 
27                            for:item="phoneNumber">
28                            <li key={phoneNumber.value}>
29                                {phoneNumber.value} ({phoneNumber.label})
30                            </li>
31                    </template>
32                    </ul>
33                </li>
34            </template>
35        </ul>  
36      </div>
37
38</template>

Note the use of the for:each directive and nested template tag to iterate through the list of contacts, and a further nested for:each directive and template to iterate through each contact’s list of phone numbers. You can do the same for email addresses, IM handles, and other contact details.

This example doesn’t import contacts into Salesforce, or otherwise use the contacts data provided from the device. It simply uses ContactsService to allow you to select contacts on the device, and then displays the returned contact data, or a status message when there’s an error.

1// contactsServiceExample.js
2import { LightningElement } from 'lwc';
3import { getContactsService } from 'lightning/mobileCapabilities';
4
5export default class ContactsServiceExample extends LightningElement {
6
7    // Component state: result status, and result contacts data
8    contactsResults = 'No contacts selected.';
9    contacts = [];
10
11    handleImportContacts() {
12
13        const myContactsService = getContactsService();
14
15        // Make sure ContactsService is available before trying to access contacts
16        if(myContactsService.isAvailable()) {
17
18            // Configuration for ContactsService
19            let options = {
20                "permissionRationaleText": 
21                    "Allow access to your contacts to enable contacts processing."
22            };
23
24            // Select on-device contacts, and then process them
25            myContactsService.getContacts(options)
26            .then((results) => {
27                this.contacts = results;
28                this.contactsResults = 'Number of contacts selected: ' + 
29                    this.contacts.length;
30            })
31            .catch((error) => {
32                // Handle cancellation, or selection errors here
33                this.contacts = [];
34                this.contactsResults = JSON.stringify(error) + 
35                    '\n\nError code: ' + error.code + 
36                    '\n\nError message: ' + error.message;
37                console.error(this.contactsResults);
38            })
39        } else {
40            // ContactsService isn't available
41            // Are you running in a supported mobile app?
42            this.contactsResults = "ContactsService API isn't available.";
43        }
44    }
45}

The component’s JavaScript logic includes handlers for the export operations. It checks for service availability before calling the export function.

1handleExportContact() {
2    // Get the ContactsService instance.
3    const myContactsService = getContactsService();
4
5    // Check if the ContactsService is available on the device.
6    if (myContactsService.isAvailable()) {
7        // Define options for the contact operation.
8        // The permissionRationaleText is displayed to the user if the app
9        // needs to request permission to access contacts.
10        let options = {
11            permissionRationaleText:
12                'Allow access to your contacts to enable contacts processing.'
13        };
14
15        // Define the contact object to be created or updated on the device.
16        let contact = {
17            name: {
18                familyName: 'Smith',
19                givenName: 'John'
20            },
21            phoneNumbers: [
22                {
23                    label: 'Work',
24                    value: '123-456-7890'
25                },
26                {
27                    label: 'Home',
28                    value: '321-654-0987'
29                }
30            ],
31            emails: [
32                {
33                    label: 'Work',
34                    value: 'jsmith@acme.com'
35                },
36                {
37                    label: 'Personal',
38                    value: 'jsmith@email.com'
39                }
40            ]
41        };
42
43        // Call putContact to save the contact to the device's address book.
44        myContactsService
45            .putContact(contact, options)
46            .then((result) => {
47                // On success, process the result.
48                this.contactExportedToDevice = JSON.stringify(
49                    result,
50                    undefined,
51                    2
52                );
53                console.log(
54                    'contactExportedToDevice: ${this.contactExportedToDevice}'
55                );
56
57                this.contactExportedResult = `Contact was added to device:\n\n${this.contactExportedToDevice}.`;
58                this.showSuccessAlert(
59                    'Exported Contact',
60                    this.contactExportedResult
61                );
62            })
63            .catch((error) => {
64                // On failure, handle the error.
65                this.contactExportedToDevice = null;
66                this.contactExportedResult = `Error code: ${error.code}\n\nError message: ${error.message}`;
67                
68                console.log('error: ' + this.contactExportedResult);
69                this.showFailureAlert(
70                    'Exported Contact',
71                    this.contactExportedResult
72                );
73            });
74    } else {
75        // If the service is not available, update the result text.
76        this.contactExportedResult = 'No Contacts Service available!';
77    }
78}