When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the chosen house. Can anyone offer insights into why this might be happening? I have attempted passing the URL in the following manner.

Todolist.ts

import { Component, OnInit } from '@angular/core';
import {NavController} from "@ionic/angular";
import { House, HouseService } from '../Services/house.service';
import { ActivatedRoute, Route, Router } from '@angular/router';
import { TodoserviceService } from '../Services/todoservice.service';
import { AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Todolist } from '../modal/Todolist';
import { Observable } from 'rxjs';
import { UserService } from '../Services/user.service';
@Component({
  selector: 'app-todolist',
  templateUrl: './todolist.page.html',
  styleUrls: ['./todolist.page.scss'],
})
export class TodolistPage implements OnInit {
  minDate = new Date().toISOString();

  house;
  currentHouse:House;
  currentHouseId: string;
  DB;
  todoArray = [];

  todo = {
    title: '',
    description: '',
    last_Date: new Date().toISOString(),

  }
  constructor(private afs: AngularFirestore,
    private router: Router,
    private houseService: HouseService,
    private userService: UserService,private navCtrl: NavController) { 
      //get ID of house from URL
      let id1 = this.router.url.split('id=');
      let id2 = id1[1].toString();
      let id3 = id2.split('/');
      let id = id3[0].toString();


      this.houseService.getHouse(id);
    if (id) {
      this.houseService.getHouse(id).subscribe(house => {
        this.currentHouse = house;
        this.house = id;
      });}
      //initialize DB             
  this.DB = this.afs.collection('house').doc(id).collection('todolist');

  this.DB.snapshotChanges().subscribe(colSnap => {
    this.todoArray = [];
    colSnap.forEach(snap => {
      let todo: any = snap.payload.doc.data();
      todo.id = snap.payload.doc.id;
      todo.last_Date = new Date(todo.last_Date).toDateString();
      this.todoArray.push(todo);
    });
  });

  }//end constructor

  ngOnInit() {
  }

  gotoAddToDo(house:string){
    this.navCtrl.navigateForward(['/add-todo',{id:house}]);
  }
}

add-todo.ts

import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { ToastController } from '@ionic/angular';
import { House, HouseService } from '../Services/house.service';
import { ActivatedRoute, Route, Router } from '@angular/router';
import { TodoserviceService } from '../Services/todoservice.service';
import { AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { Todolist } from '../modal/Todolist';
import { Observable } from 'rxjs';
import { UserService } from '../Services/user.service';

@Component({
  selector: 'app-add-todo',
  templateUrl: './add-todo.page.html',
  styleUrls: ['./add-todo.page.scss'],
})



export class AddTodoPage implements OnInit {last_Date = new Date().toISOString();

  currentHouse;
  house;
  currentHouseId;
  DB;
  todoArray = [];

  todo = {
    title: '',
    description: '',
    last_Date: new Date().toISOString(),

  }

  constructor(private afs: AngularFirestore,
              private router: Router,
              private houseService: HouseService,
              private userService: UserService) { 

                let id1 = this.router.url.split('id=');
                let id2 = id1[1].toString();
                let id3 = id2.split('/');
                let id = id3[0].toString();


                this.houseService.getHouse(id);
              if (id) {
                this.houseService.getHouse(id).subscribe(house => {
                  this.currentHouse = house;
                  this.house = id;
                });}

  //initialize DB             
  this.DB = this.afs.collection('house').doc(id).collection('todolist');

  this.DB.snapshotChanges().subscribe(colSnap => {
    this.todoArray = [];
    colSnap.forEach(snap => {
      let todo: any = snap.payload.doc.data();
      todo.id = snap.payload.doc.id;
      todo.last_Date = new Date(todo.last_Date).toDateString();
      this.todoArray.push(todo);
    });
  });

  }//end constructor

  ngOnInit() {
  }


  addtodo(){
    this.DB.add(this.todo);
    this.resetTodo();
    console.log("todoadded")
  }

  //function to reset values of bill object
  resetTodo(){
    this.todo = {
      title: '',
      description: '',
      last_Date: new Date().toISOString(),
    }
  }


}

Page displaying todos associated with a specific house

Page showing undefined URL

Answer №1

When encountering an issue, it's important to explore the possible causes. Below are examples of potential factors impacting your situation and steps you can take to address it.

  1. If you're working with {id:house}, consider sending it as a provider and loading it in the ngOnInit() of the target page. Here's how you can implement this:

    @Injectable({
       providedIn: 'root'
    })
    export class MyNavService {
       myParam: any; // Replace 'any' with an appropriate interface
    }
    

    In the calling page:

    this.myNavService.myParam = {id:house};
    await this.navCtrl.goForward('/add-todo');
    

    In the destination page:

    ngOnInit() {
       this.myObject = this.myNavService.myParam;
    }
    

    For more details on this approach, refer to this resource.

  2. Alternatively, you can send parameters similar to your current method but with some adjustments. Check out the code snippet below for guidance:

    // Send Parameter in ToDoList
    import { NavController } from '@ionic/angular';
    import { NavigationExtras } from '@angular/router';
    //...
    constructor(public navCtrl: NavController) { }
    //...
      let navigationExtras: NavigationExtras = {
      queryParams: {
          house: JSON.stringify(id),
          refresh: refresh
      }
    };
    this.navCtrl.navigateForward(['page-slug'], true, navigationExtras);
    
    // Receive Parameter add-todo
    import { ActivatedRoute } from "@angular/router";
    //...
    constructor(private route: ActivatedRoute) {}
    //...
    this.route.queryParams.subscribe(params => {
      this.refresh = params["refresh"];
      this.currency = JSON.parse(params["house"]);
    });
    

    This revised code should assist you in correctly sending and receiving parameters, avoiding undefined values and incorrect URLs. Learn more about this alternative solution here.

Note that these code samples have not been tested. They serve as a starting point for addressing issues within your application. Feel free to reach out if you found this information helpful!

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

I'm having trouble sending my token to the header because my app is not storing it correctly

Upon implementing validaToken() at login, I encounter the following error even though the token is correctly stored in local storage. I have tried putting it on the server side, but unfortunately, it does not seem to work: server.app.use( bodyParser.urle ...

Is it possible for the ionic directive "ion-nav-view" (ui-router) to be compatible with ngRoute?

I have successfully merged the Angularfire-Seed with a demo Ionic App. The integration has been smooth so far. To navigate between different views, I am looking to incorporate Ionic's functionality: // requires ui-router <ion-nav-view></ion ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

Retrieving JSON data in Angular 2

There are limited options available on SO, but it seems they are no longer viable. Angular 2 is constantly evolving... I am attempting to retrieve data from a JSON file in my project. The JSON file is named items.json. I am pondering if I can achieve th ...

Restrict the number of subscriptions allowed for an rxjs observable

Seeking a replacement for observable, subject, or event emitter that allows only one subscription at a time. The first subscriber should have priority to execute its subscribe function, with subsequent subscribers waiting their turn until the first unsubsc ...

Refreshing Custom Functions within Excel Add-On - Web Edition

Currently, I am working on an Excel Add-In that includes custom functions utilizing the Javascript API. I have been following a particular tutorial for guidance. While attempting to debug using the Web version of Excel due to its superior logging capabili ...

Angular - Turn off date selection in datepicker when toggle switch is activated

I am currently utilizing angular material and I need to figure out how to deactivate the datepicker after toggling a slide. Below is my upload form equipped with a datepicker: <form #uploadForm="ngForm" (keydown.enter)="$event.preventDefault()" (ngSub ...

Using ngFor directive to iterate through nested objects in Angular

Receiving data from the server: { "12312412": { "id": "12312412", "something": { "54332": { "id": "54332", "nextNode": { "65474&q ...

Incorporate a Google map into a table row by extending it across all table data cells

Apologies for the vague title, I am having trouble articulating my issue. Nevertheless, I am dealing with a complex HTML table structure as displayed below: <div *ngFor="let item of result; let i = index"> <table ...

What is the reason for IE displaying null when the model does not exist?

Why does IE 11 render 'null' if my model does not exist? For instance: <tr> <td [innerHTML]="model?.prop1 | my-pipe"></td> </tr> Imagine this scenario: When the page loads, a request is sent to the server and the res ...

Are there more efficient methods for locating a particular item within an array based on its name?

While I know that using a loop can achieve this functionality, I am curious if there is a built-in function that can provide the same outcome as my code below: const openExerciseListModal = (index:number) =>{ let selectedValue = selectedItems[index]; it ...

EmotionJS Component library's Component is not able to receive the Theme prop

I am in the process of developing a component library using Emotion and Typescript. However, I have encountered an issue when trying to import the component into a different project that utilizes EmotionJS and NextJS - it does not recognize the Theme prop. ...

Endpoint not returning data as expected

I'm facing an issue with my routing module where I have successfully used activatedRoute for multiple other modules but now running into trouble when implementing it in a new singular component. The structure of my routing module is as follows: const ...

How to prevent value overwriting when adding dynamic fields in Angular 7?

In my current project using Angular, I am tasked with setting up configuration using 4 specific fields: Department Name (select option) Service Name (select option) Status (text input) Level (text input). I need to be able to add multiple sets of these ...

Angular and Bootstrap button collections

Incorporating Angular with Bootstrap, we have constructed a button group as shown below: <div class="input-group-append"> <div class="btn-group" role="group"> <button class="btn btn-sm btn-outline-sec ...

Testing a subclass in Angular 6 using Karma and the @Input decorator

After finding no answers to related questions, I've decided to pose my own specific case regarding unit testing an Angular 6 component that is a subclass of a base component. The base component itself includes an @Input decorator and looks like this: ...

"Encountering a 404 error with the angular2-in-memory-web-api

Currently, I am in the process of developing a 5 minute application using Angular 2 with reference to this particular guide: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. While working on the HTTP section, I encountered a 404 error due to the a ...

How to seamlessly incorporate Polymer Web Components into a Typescript-based React application?

Struggling to implement a Polymer Web Components tooltip feature into a React App coded in TypeScript. Encountering an error during compilation: Error: Property 'paper-tooltip' does not exist on type 'JSX.IntrinsicElements' To resolve ...

Encountering "token_not_provided" error message on all GET routes in Laravel 5.3 with JWT authentication

I'm currently working on implementing authentication using Laravel 5.3 and Angular 2 with JWT. The authentication part is functioning properly, and I am able to successfully obtain the token. However, when attempting to navigate to any GET routes, an ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...