如何使用Promise内部订阅?

时间:2019-10-19 15:27:12

标签: angular ionic-framework ionic4

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

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中的引号中没有加载任何数据,但是离子存储中已加载了数据。

2 个答案:

答案 0 :(得分:1)

我认为在诺言中使用订阅不是正确的选择。您可以像下面那样更改功能,

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函数的正确方法。这也将执行您所需的相同功能。请尝试一下,如果还有其他问题,请告诉我。

答案 1 :(得分:0)

您无法返回订阅内部,因为代码将在以后执行。但是,您可以将您的订阅包装在承诺中,然后返回该承诺。

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));
            }
        });
    })
}