Blog>
Snippets

Background Sync with Service Workers

Provide an example of implementing background sync in an Angular app, allowing users to make changes offline and synchronizing when online.
// Register the service worker
if ('serviceWorker' in navigator && 'SyncManager' in window) {
  navigator.serviceWorker.register('service-worker.js')
    .then(registration => console.log('Service Worker registered'))
    .catch(err => console.log('Service Worker registration failed: ', err));
}
Checks for service worker and SyncManager support in the browser and registers the service worker from 'service-worker.js'.
// Function to be called to sync data
function syncData() {
  navigator.serviceWorker.ready.then(swRegistration => {
    return swRegistration.sync.register('syncTag');
  }).catch(() => {
    // Fallback for when Background Sync isn't supported
    // Send data to server directly
    sendDataDirectly();
  });
}

function sendDataDirectly() {
  // Implementation to send data directly to the server
  // This is used when Background Sync isn't available.
}
Defines a function to trigger a background sync. If Background Sync is not supported, it falls back to a direct server update.
// Listening for the sync event in the service worker
self.addEventListener('sync', event => {
  if (event.tag === 'syncTag') {
    event.waitUntil(syncAllData());
  }
});

async function syncAllData() {
  // Perform your data syncing tasks here
  // Typically involves sending data to the server and updating the local database upon success
}
Inside the service worker, listens for the 'sync' event and runs the data synchronization logic when triggered.
// Example Angular service method triggering the syncData function
@Injectable({
  providedIn: 'root'
})
export class DataSyncService {

  constructor() { }

  // Call this method when user performs actions to be synced later
  public syncUserActions() {
    syncData();
  }
}
Defines an Angular service with a method to trigger synchronization that wraps the syncData function, making it part of the Angular application.