【问题标题】:Page content only shows after hard refresh and not on redirect页面内容仅在硬刷新后显示,而不在重定向时显示
【发布时间】:2019-08-13 21:08:26
【问题描述】:

如何在不进行硬刷新的情况下重定向到另一条路线?

我第一次创建了一个离子/角度应用程序。这是一项调查,在用户回答了一组问题后,他们将被重定向到结果页面。

我的重定向到结果页面如下所示:

import { Router } from '@angular/router'
private router: Router
this.router.navigate(['/result/' + this.current_survey.id]);

我只能在硬刷新后看到我的结果,我不知道为什么。

发生重定向的代码在我的调查组件中,我重定向结果组件。在 ngOinit() auf 结果组件中,我从 Web 数据库中检索保存的数据,但此时数据不存在。

调查组件中的代码块如下:

if (this.current_survey.finished) {
        this.calculateResult().then((result) => {
          this.current_survey.result = result;
          this.storageService.update(this.current_survey, this.helperService.SURVEY_STORAGE).then(
            (value) => {
            this.storageService.removeKey(this.helperService.LAST_NOT_FINISHED_SURVEY);
            this.router.navigate(['result', this.current_survey.id]);
          });
        });
    }

我的结果组件中的 ngOinit 看起来:

// Check if survey is a new survey or should be load from previos surveys
    let survey_id;

    // Get id from route, if any id was given in url
    this.route.paramMap.subscribe((params: ParamMap) => {
      survey_id = params.get('id');
    });

    if (survey_id !== null) {
      survey_id = parseInt(survey_id, 10);
    }

    this.showResults(survey_id);

在我的结果组件中在 ngOinit 中调用的方法看起来:

 const key = this.helperService.SURVEY_STORAGE + '_' + survey_id;
      // Preload all neccessary data
      this.storageService.getDataByName(key).then((data) => {
        if (data.length === 0) {
            this.alertService.show('Error', '', 'Result not found :(');
        } else {
          this.survey = data.shift();
        }
      });

【问题讨论】:

    标签: javascript angular ionic-framework


    【解决方案1】:

    也许您可以提供更多信息。调查结果存储在哪里?如果它们存储在数据库中,则在结果页面组件的 ngOnInit() 方法中,您应该能够查询最新结果。另一种选择可能是,当您导航到结果页面时,您已经在调查结果完成发布之前完成了此操作。在尝试检索值之前,您可以执行以下操作以确保它已保存:

    save(surveyResults, surveyId) {
        this.someService.postResults(surveyResults)
        .subscribe(() => this.navigate(['result', surveyId]))
    }
    

    【讨论】:

    • 感谢您的回答。我添加了我的代码块的一些附加信息和背景信息。如果结果组件尝试访问,我认为你是对的,数据库目前还没有准备好。但是我把所有东西都放在了一个promise中,并在“then”块中一步一步地执行,以避免这个问题。
    • 啊。我认为您的surveyId 没有及时返回以获取结果。你可能想看看像this.route.paramMap.pipe( switchMap(params => this.showResults(params.get('id')) ).subscribe() 这样的事情,所以你确定你在调用 showResults 之前有你的路由参数。
    • 感谢您的提示。我也尝试过,但没有任何改变。我不确定如何继续处理这个问题。对我来说,一切看起来都很好,也很有意义。在函数 showResults 中,我创建了一个 console.log,它显示了正确的surveyId。也许我的函数中的 storageService 还没有准备好,但是我用 Promise 发现了这些问题,或者我对 Promise 和 async 的理解非常糟糕。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2021-12-17
    • 1970-01-01
    • 2018-04-26
    • 2023-03-08
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多