'How to consume variables in a service in angular ionic?

I'm making an app in angular ionic, where I have a service "data.services.ts" which makes the request to the API, maps, and filters the data, which I consume in "tab1.page.ts" and render in tab1. page.html. Then have a component "tab2" where I have a filter which I store in a variable called "selected_options", I want to consume this variable in the service so that the JSON is filtered and I can see only what I want to see.

data.services.ts

import { Injectable} from "@angular/core";
import { HttpClient } from "@angular/common/http";

import { map } from "rxjs/operators";
import { filter } from "rxjs/operators";

@Injectable({
    providedIn: "root"
})
export class DataService {

    constructor(private http: HttpClient) {}

    getRemoteData() {
        return this.http
        .get("https://api")
        .pipe(
            map((res: any) => {
                return res.prosugApi.filter(filter1=> {
                    return filter1.subline == "option1"
                });
            })
        );
    }
}

Replace option1 with the variable "selected_options"

tab2.page.ts

import { Component} from '@angular/core';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page{
  public selected_options: string;
  
  constructor() {}
}

tab2.page.html

<ion-header [translucent]="true">
  <ion-toolbar color="danger">
    <ion-buttons slot="start">
      <ion-back-button color="light" 
      defaultHref="/"></ion-back-button>
    </ion-buttons>
    <ion-title>Filters</ion-title>
    <ion-title slot="end">Reset</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-item>
    <ion-label>Category</ion-label>
    <ion-select interface="popover" placeholder=" Select an option" [(ngModel)]="selected_options">
      <ion-select-option value="option1">Option 1</ion-select-option>
      <ion-select-option value="option2">Option 2</ion-select-option>
      <ion-select-option value="option3">Option 3</ion-select-option>
    </ion-select>
  </ion-item>
</ion-content>


Solution 1:[1]

One Way to do this is getter and setter in service, you can set whatever value is in selected_options to some variable in service from the component and you can use that variable by getter method inside service.

inside your data.services.ts

gloabl_selected_option: any;

setSel_Opt(val: any){
  this.gloabl_selected_option = val;
}

getSel_Opt(val: any){
  return this.gloabl_selected_option;
}

inside your tab2.page.ts

import {DataService} from data.services

constructor(private dataService: DataService)

// set the below line where ever you are geting the selected_option
this.dataService.setSel_Opt(selected_option);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anna