In order to either pass a component variable as a parameter or set it as a global variable

Currently, I am in the process of restructuring my Angular2/Ionic2 code and seeking advice on the best practice for my specific situation.

Within my component, I have declared a variable (this.questions) that I need to utilize in my service method. There are two potential solutions that come to mind.

  1. One approach is to use a global variables service, store this.questions there, and then access it within foo.service

  2. Alternatively, I could simply pass the this.questions component variable as an argument in my method.

In theory, both methods should be effective, but I'm curious about the general consensus on this matter?

Here's an example code snippet pertaining to option 2:

@Component({
  selector: 'text-answers',
  templateUrl: 'text-answers.component.html'
})
export class TextAnswersComponent implements OnInit {

  questions: Object;

  constructor(public fs: FooService) {
    this.questions = {1:"foo", 2:"Bar"};
    this.fs.doPrint(this.questions)
  }

And in my foo.service.ts:

doPrint(foo){
    console.log(foo)
};

Answer №1

A more efficient approach would be to:

Define the questions object within the service itself. This assumes you intend to utilize the questions object in other components as well.

service.ts

questions:Object;

doPrint(){
    console.log(this.questions)
};

AppComponent.ts

export class TextAnswersComponent implements OnInit {
  constructor(public fs: FooService) {
    fs.questions = {1:"foo", 2:"Bar"};
    this.fs.doPrint();
}

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

Conceal Columns in DevExtreme with Angular2 EditMode

Is there a way to conceal a DataGrid Column while in EditMode by utilizing DevExtreme and Angular2? <h3>Test</h3> <dx-data-grid id="gridContainer" [dataSource]="xxx" [allowColumnReordering]="true" [allowColumnResizing]="true" [rowAltern ...

Angular Reactive Forms: Implementing Error Display and Red Border Styling

Recently, I've started diving into Angular Reactive Forms and I'm quite impressed by the async validator feature for tasks that involve checking data against a database. The separation of validation rules from the GUI is also very appealing to me ...

Enhance your Primeng split button with an added icon when selected

Is it possible to add a tick icon when the user selects the click option in a split button? Any advice on how to achieve this would be appreciated. Thank you. For example, similar to the image below: https://i.stack.imgur.com/owOgE.png ...

Tips for verifying the presence of an active session after closing the browser

Here is my situation: When a user logs into the app and then opens another browser window, they are already authenticated thanks to express-session, bypassing the login page. This pattern continues for subsequent browser windows. The issue I am facing no ...

Managing the lifecycles of extended class instances in Angular 2 - what's the best approach?

The code snippet below is causing an issue for me in Angular 2.4.9: export class MyComponent extends BaseComponent implements OnInit { type = 2; constructor() { super(); } ngOnInit(){ console.log('inited type', this.type) } } ...

Making calls to an Angular GRPC API through an Envoy proxy

Having trouble connecting to the GRPC server from the UI via Envoy. Here's the code snippet for the Envoy proxy: static_resources: listeners: - address: socket_address: address: 0.0.0.0 port_value: 8888 filter_chains: ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

The functionality of Angular 9 Service Worker appears to be inhibited when hosting the site from a S3 Static Website

I created a Progressive Web Application (PWA) following these steps: Started a new Angular app using CLI 9.1.8; Added PWA support by referring to the documentation at https://angular.io/guide/service-worker-getting-started; Built it with ng build --prod; ...

Encountering an issue with applying D3 fill to a horizontal stacked bar chart in Angular using TypeScript. When using .attr("fill", ..) in VSC, an error stating "No overload matches this call" is displayed

My goal is to create a stacked horizontal bar chart in d3, and I've been following the code example provided here. To showcase my progress so far, I have set up a minimal reproduction on stackBlitz which can be found here. While there are no errors ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order t ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

A mistake was made: The template contains errors stating that 'app-my-profile' is an unknown element

I encountered an error message: "Uncaught Error: Template parse errors: 'app-my-profile' is not a known element," while working on setting up my profile service. import { BrowserModule } from '@angular/platform-browser'; import { NgM ...

The video element in my Angular application is not functioning properly in Safari

I am having an issue with playing a video in my angular app. It works perfectly in all browsers except for Safari : <video controls autoplay muted class="media"> <source src="https://my-site/files/video.mp4" type="video/mp4" /> </video& ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

I am encountering a PeerInvalid error when attempting to launch myapp on an Android device using Ionic/Angular 4

For the past 3 days, I've been using Ionic and today I decided to try putting my application on my Android devices. However, I've encountered a problem... When I run: ionic cordova run android --device -l -debug I'm getting these errors th ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

Proper management of setTimeout in an Angular application

I am working on a one-page web application where the main component's ngOnInit() function triggers a recursive function called loopDoSomething() using setTimeout: ngOnInit(): void { // Perform some operations this.loopDoSomething(); } loopDoSome ...

issue with global variable not functioning properly within a sub-function in Angular 7

I have a question that needs clarification import { Component, OnInit,ViewChild,ElementRef } from '@angular/core'; import {Http,Headers} from "@angular/http"; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, ...

Using TypeScript to chain observables in a service and then subscribing to them in the component at the end

Working with Platform - Angualar 2 + TypeScript + angularFire2 Within my user.service.ts file, I have implemented the following code to initiate an initial request to a firebase endpoint in order to fetch some path information. Subsequently, I aim to util ...