I have a service in Angular 7 that calls an API and I want to use some data gathered by a component in the API call. Here is the relevant portion of the component:
import { Component, OnInit } from "@angular/core";
import { IPrompt } from './prompt';
import { PromptService } from './prompt.service';
import { DropdownService } from '../dropdown.service'
import { FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
import { IQuery } from './prompt'
import { NgxSpinnerService } from 'ngx-spinner';
import { Query } from '../dropdown.service';
@Component({
selector: 'pm-prompts',
templateUrl: './prompt-list.component.html',
styleUrls: ['./prompt-list.component.css']
})
export class PromptListComponent implements OnInit
{
public get searchArray(): string[]
{
return [ this.searchForm.controls['searchQuery'].value, this.searchForm.controls['region'].value,
this.searchForm.controls['status'].value, this.searchForm.controls['language'].value,
this.searchForm.controls['inputMode'].value ];
}
public get QueryString(): string
{
var query = new Query(this.searchForm.controls['searchQuery'].value, this.searchForm.controls['region'].value,
this.searchForm.controls['status'].value, this.searchForm.controls['language'].value,
this.searchForm.controls['inputMode'].value, this.searchArray);
return query.getQuery;
}
}
I removed all the unnecessary fields from the above sample. Basically, I want to access the get QueryString() method that is in this component from my service called PromptService. I can include the code for the service as well if needed. I've researched this but all of the questions I see has asked how to use data from a service in a component, not the other way around.
I tried importing the component to the service then using:
queryString = PromptListComponent.QueryString()
But I get an error saying that "Property 'QueryString' does not exist on type 'typeof PromptListComponent'". I feel that there is a simple fix for this but I have had no luck finding it or figuring it out.
You can import the component to the service and define it in your constructor, it generate an instance of that component, then you can access methods and properties from that component's instance:
In your service file:
import { PromptListComponent } from './path-to-your-component';
import { Injectable } from '@angular/core';
@Injectable({providedIn:'root'}) //Or import to providers
export class PromptService {
//Define it in your service constructor
constructor( private promptListComponent: PromptListComponent){}
//You now have generated an instance of that component
getQueryFromPromtListComponent() {
console.log(this.promptListComponent.QueryString())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With