【问题标题】:How to use subscribe inside promise?如何在承诺中使用订阅?
【发布时间】:2019-10-20 00:32:02
【问题描述】:

我的应用程序检查 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 中的引号中没有加载数据,但数据已加载到离子存储中。

【问题讨论】:

    标签: angular ionic-framework ionic4


    【解决方案1】:

    我认为在 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函数的正确方式。这也将执行您需要的相同功能。请尝试一下,如果您发现任何其他问题,请告诉我。

    【讨论】:

      【解决方案2】:

      您不能在订阅内部返回,因为代码稍后会执行。但是,您可以将您的 subscribe 包装在一个 Promise 中并返回该 Promise。

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

      【讨论】:

        猜你喜欢
        • 2019-08-31
        • 2017-09-21
        • 2017-12-12
        • 1970-01-01
        • 2016-06-26
        • 2017-07-29
        • 1970-01-01
        • 2020-04-09
        • 2021-12-09
        相关资源
        最近更新 更多