How to assign data from chrome.storage to Angular component's variable

257 Views Asked by At

How can I assign data from chrome.storage.sync.get to my Angular component's variable?

Here is my component:

export class KTableComponent implements OnInit {

  words: string[] = [];

  constructor() {
  }

  ngOnInit(): void {
  }

  loadData() {
    const words = this.words;
    chrome.storage.sync.get({words: []}, function (result) {
      Object.assign(words, result.words)
    });
   // I want to stop here until data retrieved
  }

My goal is to retrieve data and after assigning that data to words variable, render component again. I know that chrome.storage.sync.get works asynchronously and I don't know, how to wait for the result.

1

There are 1 best solutions below

0
Prajwal On

What you need to do, is to wait until you get the response back and show the result.

You code should,

  • know when the data is loading.
  • update when data is loaded

I would rewrite it in thing format.

words: string[] = [];
loading = false;

 loadData() {
    const words = this.words;
    loading = true;
    chrome.storage.sync.get({words: []}, this.onDataLoad);

onDataLoad(result) {
      loading = false;
      Object.assign(words, result.words);
    }

With this code, you can show a loader while data is being synced, and Angular will update the view for you, when words get values assigned.

If you would like to do until there are values for word object, you can write it in onDataLoad.