Accessing a variable from different tabs in an Ionic 3 weather application

I am currently exploring the world of app development and have decided to create a weather application. The main goal of this app is to display the current weather using data from the openweathermap.org API. To achieve this, I have divided my app into 3 tabs:

  • The first tab (Home) will display the weather data.
  • The second tab contains information about the creators (credits, useless).
  • And the third tab focuses on the logic behind the app.

One challenge I am facing is related to the Ionic "Select" element in the third tab. Users should be able to choose one of the 4 predefined locations (Zwettl, Krems, St. Pölten, Wien). Depending on their selection, the temperature of that location should be displayed on the first tab. For instance, if a user picks Zwettl, the app should show the current temperature in Zwettl on the first tab.

My question is: How can I define the value of the selected location using an 'ion-option' and how can I access this variable in the first tab or the tab1.page.ts file?

Please disregard the checkboxes in picture 2 as I am focusing on determining what specific data to display on the first tab (temperature, humidity, etc.) once the navigation between tab1 and tab3 is functional. I hope this clarifies my query!

Below is the code I have implemented so far:

Tab1.html:

<ion-content [fullscreen]="true">
  <ion-item>    
    <ion-label>
      <p id="weatherdata"></p>
      <h3>{{weather?.main.temp}}°C</h3>
      <ion-button (click)="setLocation1()">Zwettl</ion-button>
      <ion-button (click)="setLocation2()">Wien</ion-button>
    </ion-label>
  </ion-item>
</ion-content>

Tab1.ts:

import { Component } from '@angular/core';
import { ApiService } from './../api.service'
import { HttpParams } from '@angular/common/http';

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

export class Tab1Page {
  currentDate;
  weather: any;

  constructor(public api: ApiService) {
    this.currentDate = new Date();
  }

  ngOnInit(){
    this.api.loc = "Zwettl";
    this.getWeather();
  }

  setLocation1(){
    this.api.loc = "Zwettl";
    console.log(this.api.loc);
    this.getWeather();
  }

  setLocation2(){
    this.api.loc = "Wien";
    console.log(this.api.loc);
    this.getWeather();

  }

  async getWeather(){
    await this.api.getWeatherData().subscribe(res => {
      console.log(res);
      this.weather = res;

    }, err => {console.log(err);
    });
  }  
}

Tab3.html:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Settings  
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-list>
    <ion-item>
      <ion-icon name="compass"></ion-icon>
      <ion-label style="padding-left:15px">Location</ion-label>
      <ion-select placeholder="Select One">
        <ion-select-option value="zwettl">Zwettl</ion-select-option>
        <ion-select-option value="krems">Krems</ion-select-option>
        <ion-select-option value="stpoelten">St. Pölten</ion-select-option>
        <ion-select-option value="wien">Wien</ion-select-option>
      </ion-select>
    </ion-item>
  </ion-list>
</ion-content>

API.ts:

import { Injectable } from '@angular/core';
import {Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpHeaders, HttpParams, HttpErrorResponse} from '@angular/common/http';
import{catchError, tap, map} from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type' : 'application/json'})
};
@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http:HttpClient) { }

  loc:any;


  getWeatherData(): Observable<any>{
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type' : 'application/json'})
    };
    const request = this.http.request<any>('GET', "http://api.openweathermap.org/data/2.5/weather?q="+this.loc+"&APPID=99b52e0a2655a753716cf6adb17476a7&units=metric")

            request.subscribe(response => {
                /Handling the response body/
            }, error => {
                console.log(error);
            });
            return request.pipe()

  }
}

There isn't anything significant in Tab3.ts :(

Answer №1

Utilize rxjs subject to establish observable value in any part of the application

Create a service for setting and retrieving the observable value

Global-foo.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class GlobalFooService {

  constructor() { }

  private fooSubject = new Subject<any>();

  publishData(data: any) {
    this.fooSubject.next(data);
  }

  getObservable(): Subject<any> {
    return this.fooSubject;
  }
}

Tab3.ts

this.globalFooService.publishSomeData({
      foo: 'bar'
    });

Tab1.ts

this.globalFooService.getObservable().subscribe((res) => {
    console.log(res);
}

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

Running a TypeScript file on Heroku Scheduler - A step-by-step guide

I have set up a TypeScript server on Heroku and am attempting to schedule a recurring job to run hourly. The application itself functions smoothly and serves all the necessary data, but I encounter failures when trying to execute a job using "Heroku Schedu ...

Tips for modifying the language of an Angular Application's OneTrust Cookie Banner

I'm currently developing an Angular application and utilizing OneTrust for managing cookie consent. The issue I'm encountering is that while the rest of the components on the login page are properly translated into the target language, the OneTru ...

Modify the parent property's value within a derived Angular service

I'm utilizing Angular 9 and I have Service A along with Service B which extends Service A. Within Service A, there's a specific property that I aim to modify its value from within Service B. Surprisingly, the change only reflects in Service B and ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

Exploring the concept of object destructuring in Typescript with imports

Currently, I am in the process of developing the type system for @masala/parser. This allows me to customize the index.d.ts file to fit my needs. When using this as a user, I can: import masala from '@masala/parser' let {C, Stream, F} = masala; ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

I am looking for a way to convert the date format from "yyyy-MM-dd" to "dd-MM-yyyy" in NestJs

I need help with changing the date format from "yyyy-MM-dd" to "dd-MM-yyyy". Currently, my entity code looks like this: @IsOptional() @ApiProperty({ example: '1999-12-12', nullable: true }) @Column({ type: 'date', nullable: true } ...

Preventing Repeated Form Submissions in Angular: A Helpful Guide

`Hello, I am new to Angular and I am struggling with a specific part of the form. People have been clicking the submit button multiple times quickly, causing the same information to be added repeatedly before it can be sent to the API. I have searched onl ...

Customize the style of Angular Material within an Angular component

In my Angular component, I am utilizing Material 2's <md-input-container>. I am looking to customize a specific class, such as .mat-input-wrapper, that is originally defined in Angular Material. However, my intention is for this customization to ...

Styling your Angular project with CSS

I have a folder called about which contains a file named about.component.css . I want the background-color to be set to aqua only for the page about.component.html. When I try setting the background-color in about.component.css like this: body { backg ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Utilize Typescript to Invoke Functions of Different Components in Angular 2

Hello everyone, I am a newcomer to Angular 2 and I'm looking to utilize the value of one component in another component. This will help me populate data based on that particular value. In my setup, I have three Components - App.Component, Category.Co ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

Tips for keeping your Angular CDK up to date and improving its performance

Having just started with Angular, I'm stuck trying to figure out why the update is throwing errors. Purpose: Update the cdk and material versions, then install file-saver. Command: npm update @angular/cdk How can I update my angular cdk? Here&apos ...

What is the best way to handle installing peer dependencies when using Angular CLI?

Every time I try to update my Angular CLI and NPM, I get stuck in a cycle of errors. After updating, I receive WARN messages instructing me to install peer dependencies (listed below). However, when I try to install these dependencies, more WARN messages a ...

What could be causing the React text input to constantly lose focus with every keystroke?

In my React project using Material-UI library, I have a component called GuestSignup with various input fields. const GuestSignup = (props: GuestSignupProps) => { // Component code goes here } The component receives input props defined by an ...

Using path aliases in a Typescript project with Typescript + Jest is not a viable option

Note I am able to use aliases in my TypeScript file. Unfortunately, I cannot use aliases in my test files (*.test.ts). My Configuration 1. Jest.config.ts import type { Config } from '@jest/types'; const config: Config.InitialOptions = { ve ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

In Angular, I aim to invoke the this.addDispatchToReceive method whenever the outcome is successful within each forEach iteration

How can I ensure that the values from this.stockItemDispatch are obtained in this.addDispatchToReceive(); during each iteration of a loop, instead of only getting the last stock value? The issue is that the subscribe function runs after the foreach cycle ...