Newer Version Available
Use the ContactsService API
- Import ContactsService into your component definition to make the ContactsService API functions available to your code.
- Test to make sure ContactsService is available before you call contacts-related functions.
- Use the getContacts() function to select and access contacts.
Add ContactsService to a Lightning Web Component
In your component’s JavaScript file, import ContactsService using the standard JavaScript import statement. Specifically, import the getContactsService() factory function from the lightning/mobileCapabilities module, like so:
1import { getContactsService } from 'lightning/mobileCapabilities';After it’s imported into your component, use the factory function to get an instance of ContactsService. With your ContactsService instance, use the utility functions and constants to verify availability. Then use contacts-related functions to select contacts from the device.
Test ContactsService Availability
ContactsService depends on physical device hardware and platform features. A component that uses ContactsService renders without errors on a desktop computer or in a mobile browser, but contacts-related functions fail. To avoid these errors, check if ContactsService functionality is available before you use it.
1handleGetContactsClick(event) {
2 const myContactsService = getContactsService();
3 if(myContactsService.isAvailable()) {
4 // Perform contacts-related operations
5 }
6 else {
7 // ContactsService not available, or consuming app hasn’t implemented it
8 // Not running on hardware with contacts, address book, etc.
9 // Handle with message, error, beep, and so on
10 }
11}Access and Process Contacts
It’s straightforward to create a custom contacts processing feature using ContactsService.
- Open the contacts selection list view using getContacts().
- Your user selects contacts from the list.
- Process the results (the contacts data for the selected contacts).
For example:
1// Select on-device contacts, and then process them
2myContactsService.getContacts(options)
3.then((results) => {
4 // Do something with the contacts data
5 this.contacts = results;
6 console.log(results);
7})
8.catch((error) => {
9 // Handle cancellation, or selection errors here
10 this.contacts = [];
11 console.error('Error code: ' + error.code); +
12 console.error('Error message: ' + error.message);
13});See getContacts(options) for more details about how to handle contacts data, handle errors, and so on.