简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM