Using a variable within an Angular 2 Component provider

Is it possible for a component to offer a service based on its inputs? In my situation, my component relies on a service provided by another firebase service, and I am looking to have the component create a new firebase service with a child element, allowing the other service to only access this specific part of the database.

Currently, my solution involves the component calling the service's setChild function to specify the child element. However, I am interested in exploring if it is feasible to achieve this in the manner described above.

Thank you, Tamas

Answer №1

Unfortunately, it is not possible to access the component instance when evaluating decorator arguments.

However, a workaround is to inject the service into the component where it is included in the providers and pass the value to the service. This way, when a child component also injects the same service, they will share the same value:

@Injectable()
class MyService {
  ... 
}

@Component({
  selector: 'parent',
  template: 'x'
  providers: [MyService],
)}
class Parent {
  @Input() someInput;

  constructor(private myService:MyService) {
  }

  ngOnChanges() {
    this.myService.sharedValue = this.someInput;
  }
}

@Component({
  selector: 'descendant',
  template: 'x'
)}
class Descendant {
  constructor(myService:MyService) {
    myService.sharedValueChange.subscribe(val => {
      console.log(val);
    });
  }
}

For more information on creating a shared service using Observable to notify about changes, you can visit Delegation: EventEmitter or Observable in Angular2

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

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

Encountering a Problem with vue-check-view Library in Typescript

After successfully declaring the js plugin with *.d.ts, I encountered an issue where my view was blank after using .use(checkView). Does the library vue-check-view support Typescript? Error: Uncaught TypeError: Cannot read property '$isServer' o ...

The parent route guard in Angular triggers an infinite loop when navigating to a child route from the parent route

Imagine a scenario where we have a website containing profiles of various users, accessible only to authenticated users. I want the ability to enter an empty URL and then, upon authentication, be redirected to my profile. Additionally, I would like to dire ...

How come Angular sets the empty value of a number input to null?

Curiosity strikes me as I ponder on the reason why in reactive forms of Angular, input fields with an attribute type='number' display a value of null when they are left empty. This behavior is quite different from what we observe in native HTML5 ...

Converting a dynamic JSON object into a generic type in TypeScript

I need assistance with converting a JSON object into the equivalent generic type in TypeScript. The JSON object I have contains dynamic keys such as applications and permissions. The keys inside applications, like application_management and user_managemen ...

Error handling in Angular 6/Express: Route malfunction

I'm currently working on developing a nodeJS/Angular 6/Express application. In the Express part of the app, there's only one route for the "back-end" while Angular has multiple routes. Everything runs smoothly on my local machine, but when I att ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

What is the best way to add a search bar for filtering a table efficiently?

I have a collection of applications stored in a table, each with two specific columns - appAcronym and appName. The table consists of approximately 250 rows of different applications. My goal is to incorporate a search feature at the top of the table or in ...

The formControl value is not being shown on the display

I am facing an issue with a form that has multiple fields created using formGroup and formControlName. The challenge arises when I launch the application and need to retrieve data from the back end to display it on the view. The specific problem I'm ...

Utilize the ref attribute when working with Material UI InputLabel components

Is there a way to access the ref parameter of an InputLabel from the @material-ui/core library using TypeScript? When I attempt to do so, the following code produces an error related to ref: TS2769: No overload matches this call. export class ComboBo ...

Optimizing an ASP.NET web application for seamless integration with Angular 2 and TypeScript

For the past couple of days, I have been delving into angular2. I am curious to understand the process of configuring my project to effectively utilize angular2 and typescript. My development environment is Visual Studio 2015. Can you guide me on the nec ...

Inject variables into [ngModel] in Angular version 2

I need to pass a variable into [ngModel] but I'm unsure of the correct syntax. Can someone help me determine if this code is accurate? <select [ngModel]=this.audutModel (ngModelChange)="AddAdults($event)"> ...

Get the HTML content from a component that has been imported

Is it possible to access the HTML content of an imported component in Ionic2/Angular2? For instance: import {A} from '../../components/a/a'; console.log(A.html()); I am looking for a way to achieve something similar to this - even though ther ...

Mastering unit testing with Behaviour Subjects in Angular

I am looking to test the get and set methods of my user.store.ts file. The get() method is used to retrieve users, while addUsers() is utilized to add new Users to the BehaviorSubject. How can I accomplish this? import { Injectable } from '@angular/c ...

Sending data to Dialog Component

While working on implementing the dialog component of material2, I encountered a particular issue: I am aiming to create a versatile dialog for all confirmation messages, allowing developers to input text based on business requirements. However, according ...

The Angular component exported from one module cannot be utilized in a different module

Why am I unable to use a custom component exported in my AppModule within another module that is imported into the AppModule? Isn't an exported component supposed to be visible globally? I am attempting to utilize the CalendarComponent with the selec ...

Using react-scripts leads TypeScript to mistakenly search for the incorrect file to import

Currently utilizing React and Relay in my project, I've encountered an issue with TypeScript. After relocating the directory where Relay generates some TypeScript files that are included in my app, TypeScript is unable to find them, presenting an unus ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

Rendering HTML content in a preformatted <code> tag using Electron

Recently, a brand new electron/angular application was built with the code snippet running in main.ts: win.loadURL(url.format({ pathname: path.join(__dirname, 'dist/index.html'), protocol: 'file:', slashes: true })); After launc ...

Issue with page reload in Angular 8 when URL contains a dot

When the URL contains a dot(.) and we attempt to reload the page using the browser's reload function, the following error occurs: The resource you are seeking has been deleted, its name has been changed, or it is currently unavailable. We prefer not ...