【问题标题】:Ionic 4 ngOnInit is not called after navigate导航后不调用 Ionic 4 ngOnInit
【发布时间】:2020-06-09 01:45:57
【问题描述】:

我是 ionic Angular 的新手,正在编写教程。

为了更好地理解,假设有页面 A 和 B。

下面是页面B的代码

pageB.ts

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service'
import { Router } from '@angular/router'

@Component({
  selector: 'app-news-single',
  templateUrl: './news-single.page.html',
  styleUrls: ['./news-single.page.scss'],
})
export class NewsSinglePage implements OnInit {

  article: any;

  constructor(private newsService: NewsService, private router: Router) {
  }

  ngOnInit() {
    console.log("ngOnInit")

    if(!this.newsService.currentArticle) {
      this.router.navigate(['/news']);
    }
    this.article = this.newsService.currentArticle;
  }

}

pageB.html

<ion-card class = "ion-margin-vertical">
      <img [src] = "article.urlToImage"/>
      <ion-card-header>
        <ion-card-title>{{article.title}}</ion-card-title>
      </ion-card-header>

      <ion-card-content>

      {{article.description}}
      </ion-card-content>
</ion-card>

这就是问题所在。

当我在页面 B 上刷新时,会调用 ngOninit()

由于 this.newsService.currentArticle 变得未定义,它导航回页面 A

然后,当我从 page A 导航到 page B 时,不会调用 ngOninit() 并且 article是 仍然未定义。

我曾尝试使用 ionviewwillenter(),但它会出现错误。

可能不是一个好习惯,因为我在创建组件后插入数据。

我希望我已经把我的问题说清楚了。

现在,我不确定它是否是一个错误,因为我不完全了解 Angular 在生命周期挂钩方面的工作原理以及 ionic 如何使用 Angular 使其工作。

我现在有几个问题。

  1. 将数据放入服务中是否是一种好习惯,因为它在刷新后变得未定义??

  2. 刷新期间如何处理数据?

提前谢谢你。


编辑

在我使用 ionViewWillEnter 加载与 ngOninit 相同的数据后,

文章显示错误。

当我进行以下操作时会发生此错误。

刷新页面B->导航到页面A->点击导航到页面B

【问题讨论】:

    标签: angular ionic4


    【解决方案1】:

    ngOnInit() 将在页面第一次打开时运行

    ngOnInit() {
       // Actions
    }
    

    ionViewWillEnter() 将在每次导航到页面时运行,就在页面打开之前,适用于预加载内容。

    ionViewWillEnter(){
       // Actions
    }
    

    ionViewDidEnter() 将在每次页面导航到时运行

    ionViewDidEnter(){
       // Actions
    }
    

    注意:字母区分大小写

    【讨论】:

      【解决方案2】:

      您可以使用 IonViewDidEnter 生命周期钩子来调用页面 B 上的服务。

      【讨论】:

      • @Xd。如果这有助于您解决问题,请接受它作为答案。
      • 当我使用 IonViewDidEnter 调用服务时,错误仍然存​​在。 ERROR TypeError: Cannot read property 'urlToImage' of undefined
      • 我添加了照片以便更好地理解。
      • 确保在调用服务后控制您的文章变量并检查它是否未定义或为空,然后创建一个新的字符串变量,例如imgUrl = "" & 分配 (imgUrl = this.article.urlToImage)。然后将此变量分配给 src 指令 ([src] = "imgUrl")
      猜你喜欢
      • 2023-03-09
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      相关资源
      最近更新 更多