Issues with Router navigation in an Ionic-Angular application

I am currently working on a straightforward application using Angular 9 and Ionic 5. The main page consists of a list of items.

Here is my HTML code:

<ion-header>
  <ion-toolbar>
    <ion-title>recipes</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list>
    <app-recipe-item *ngFor="let recipe of recipes" [recipeItem]="recipe">
    </app-recipe-item>

  </ion-list>
</ion-content>

And here is my TypeScript code:

import { RecipesService } from './recipes.service';
import { Recipe } from './recipes.model';
import { Component, OnInit, OnChanges, SimpleChanges } from '@angular/core';

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

  recipes: Recipe[];

  constructor(
    private recipesService: RecipesService
  ) { }

  ngOnInit() {
    this.recipes = this.recipesService.getAllRecepies();
  }

  ngOnChanges(changes: SimpleChanges) {
  }

}

Upon clicking an item in the list, I am directed to a detailed page for that item where I have the option to delete it.

HTML:

<ion-header>
  <ion-toolbar color="primary">
    <ion-button slot="start">
      <ion-back-button defaultHref="/recipes"></ion-back-button>
    </ion-button>
    <ion-title>
      {{ loadedRecipe.title }}
    </ion-title>
    <ion-button slot="primary" (click)="onDeleteRecipe()">
      <ion-icon slot="icon-only" name="trash"></ion-icon>
    </ion-button>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-grid fixed class="ion-no-padding">
    <ion-row>
      <ion-col class="ion-no-padding">
        <ion-img [src]="loadedRecipe.imageUrl"></ion-img>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col size="12">
        <h1 class="ion-text-center">{{ loadedRecipe.title}}</h1>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col size="12">
        <ion-item *ngFor="let ig of loadedRecipe.ingredients">
          {{ ig }}
        </ion-item>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

TypeScript:

import { RecipesService } from './../recipes.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Recipe } from '../recipes.model';
import { AlertController } from '@ionic/angular';
    
@Component({
  selector: 'app-recipe-detail',
  templateUrl: './recipe-detail.page.html',
  styleUrls: ['./recipe-detail.page.scss'],
})
export class RecipeDetailPage implements OnInit {

  loadedRecipe: Recipe;

  constructor(
    private activatedRoute: ActivatedRoute,
    private recipeService: RecipesService,
    private router: Router,
    private alertCtrl: AlertController
  ) {}

  ngOnInit() {
    this.activatedRoute.paramMap.subscribe(paramMap => {
      if (!paramMap.has('recipeId')) {
        // redirect
        this.router.navigate(['/recipes'])
        return;
      } else {
        const recipeId = paramMap.get('recipeId');
        this.loadedRecipe = this.recipeService.getRecipe(recipeId);
      }
    });
  }

  onDeleteRecipe() {
    this.alertCtrl.create({
      header: 'Are you sure?',
      message: 'Do you want to delete the recipe?',
      buttons: [{
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Delete',
          handler: () => {
            this.recipeService.deleteRecipe(this.loadedRecipe.id);
            this.router.navigate(['/recipes']);
          }
        }
      ]
    }).then(alertEl => {
      alertEl.present();
    });
  }

}

After deleting an item, I am returned to the main page with all the items still displayed. The onInit method is not triggered, so the updated list of items is not reflected. Clicking on the deleted item leads to a blank page as the item no longer exists. What steps should I take to ensure that the deleted item is no longer visible on the main page?

Answer №1

If you're experiencing this issue, it could be due to caching in Ionic.

To ensure that certain code is loaded every time, you can place it within the ionViewWillEnter method.

ionViewWillEnter() {
  // Add code here to load every time.
}

In your RecipesPage, update

 ngOnInit() {
    this.recipes = this.recipesService.getAllRecepies();
 }

to

ionViewWillEnter() {
   this.recipes = this.recipesService.getAllRecepies();
}

Answer №2

Place it within the designated service

availableRecipes:any[]=[];

To accomplish this, simply set up a service and input an array, then utilize the splice method

const recipeIndex = this.ADDITIONAL_SERVICE.availableRecipes.findIndex(item => item.id === +this.currentRecipe.id)
if (recipeIndex >= 0){
    this.ADDITIONAL_SERVICE.availableRecipes.splice(recipeIndex,1)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Table pagination in Mat is experiencing overflow, and the button styles have also been customized for a unique look

I implemented a mat paginator feature, however, I am facing an issue where the alignment of items per page options is not correct. Below is the snippet from component.html file: <div class="table-responsive" *ngIf="resultssummaries"> &l ...

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

"Encountering a Challenge: Cannot Assign Array to ngFor Directive in Ionic App, Displaying

I have encountered an issue while fetching product categories using API. The problem lies in the fact that the categories are being retrieved as an object instead of an Array which is required for *ngFor to work in Ionic. Any assistance on how to define th ...

Runtime not able to identify new modifications post migration from Angular 2 to Angular 6

I successfully upgraded my Angular 2 project with DotNetCore to Angular 6 by executing the following command: npm install -g npm-check-updates ncu -u After completing the migration process, I found that while I can still run my previously developed proje ...

Guide on upgrading an Angular project to a targeted version with its corresponding dependencies

I'm embarking on reviving a previous angular venture. My objective is to bring it up-to-date with a particular version along with upgrading all its affiliated dependencies to the most recent ones. I attempted by initially uninstalling the CLI version, ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

Switching templates within a component based on conditions in Angular 2

Situation: I am working with a component called COMP that needs to load one of two templates, which are named TEMPLATE_1 and TEMPLATE_2. The choice between the two is based on the type of user who is logged in - either an ADMIN user or a NORMAL user. Can ...

Rendertron always renders base routes as empty

I'm running into an issue while trying to use rendertron via an Apache proxy - all the base routes are showing up as "null." Could this be due to a configuration error on my part? Any help would be greatly appreciated. The Rendertron service is curre ...

Angular 2: Changing the name of a component

Looking for guidance on renaming a component in my Angular2 application. I've already updated all the necessary files - changed the file names and folder name, as well as made adjustments to specific files such as y.component.ts, app.routing.ts, and a ...

There is no way for me to view my loader more than once

I am currently utilizing @ng-bootstrap/ng-bootstrap for pagination and ngx-loading to handle loader display. Both of these components are performing well in my application. Here is the code snippet for pagination: {{ loading }} <ngb-pagination [colle ...

We encountered an unhandled error: It is impossible to assign a value to the property '_showWarnings' of the object '#<Object>'

Looking to implement SSR on my current website. Angular version: v8 Followed the instructions from this link: https://angular.io/guide/universal [error] TypeError: Cannot assign to read only property '_showWarnings' of object '#<Object& ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

Updating the latest version of Typescript from NPM is proving to be a challenge

Today, my goal was to update Typescript to a newer version on this machine as the current one installed is 1.0.3.0 (checked using the command tsc --v). After entering npm install -g typescript@latest, I received the following output: %APPDATA%\npm&b ...

The unfamiliar module 'Ng2SmartTableModule' was unexpectedly declared within the 'AppModule'

I am currently exploring ng2 smart table through this link and encountering an error. An unexpected module 'Ng2SmartTableModule' was declared by the module 'AppModule', resulting in the following error: Uncaught Error: Unexpected modul ...

Angular variable encounters an error while attempting to assign the returned object

Upon receiving an object from the server and attempting to assign it to a variable within an Angular component object, I am encountering an exception. Can anyone provide insight into what may be missing or causing this issue? product-component.ts import ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

What is the best approach for incorporating a customized set of valid keywords into a text input field in JHipster while maintaining a sophisticated design?

My code snippet is not displaying the input even though all the necessary elements are in place: home.component.ts <p class="lead">Input: </p> <div><jhi-calculator-input></jhi-calculator-input></div> calculator.compon ...

Preserve the checkbox state upon refreshing the page

I am facing an issue with keeping the checkbox state saved after a page reload. Currently, I have stored my unchecked checkboxes in localStorage, but I am unsure about what steps to take next. In simple terms, I want the checkbox to remain unchecked when I ...