如何在承诺中使用订阅?

How to use subscribe inside promise?

我的应用程序检查 Ionic 存储中是否有数据,如果有 none,它会将数据从 JSON 文件加载到 Ionic 存储中。这是我的代码:

quote.page.ts

quotes: Quote[] = [];
this.plt.ready().then(() => {
  this.storageService.loadQuotes().then(quotes => {
    this.quotes = quotes;
  });
});

storage.service.ts

quotes: Promise<Quote[]>;
data: any;

loadQuotes(): Promise<any> {
return this.storage.get(QUOTES_KEY).then((quotes: Quote[]) => {
  if (!quotes || quotes.length === 0) {
    this.http.get("../../assets/files/quotes.json").subscribe(result => {
      this.data = result["quotes"];
      this.quotes = result["quotes"];
      this.storage.set(QUOTES_KEY, this.data);
      return this.quotes;
    });
  }
});
}

我的问题是,quote.page.ts 中引号中没有加载数据,但离子存储中加载了数据。

我认为现在不适合在 promise 中使用 subscribe。您可以像下面这样更改您的功能,

storage.service.ts

  async loadquotes(): Promise<any>{
   this.storage.get(QUOTES_KEY).then((quotes: Quote[]) => {
     if (!quotes || quotes.length === 0) {
        let response = await this.http.get("../../assets/files/quotes.json").toPromise();
        this.data = response ["quotes"];
        this.quotes = response ["quotes"];
        this.storage.set(QUOTES_KEY, this.data);
        return this.quotes;
    }
});

quote.page.ts

this.quotes = await this.storageService.loadQuotes();

这才是promise函数的正确使用方式。这也将执行您需要的相同功能。请试试这个,如果您发现任何其他问题,请告诉我。

您不能在 subscribe 中 return,因为代码稍后会执行。但是,您可以将您的订阅包装在一个承诺和 return 该承诺中。

loadQuotes(): Promise<any> {
    return this.storage.get(QUOTES_KEY).then((quotes: Quote[]) => {
        return new Promise((resolve, reject) => {
            if (!quotes || quotes.length === 0) {
                this.http.get("../../assets/files/quotes.json").subscribe(result => {
                    this.data = result["quotes"];
                    this.quotes = result["quotes"];
                    this.storage.set(QUOTES_KEY, this.data);
                    resolve(this.quotes);
                }, (error) => reject(error));
            }
        });
    })
}