0

I created an Angular app (which consists out of a Service and a listcomponent) to call an api and dispatches actions, but the error comes when i use functions from the listcomponent component. I put the component in the constructor to use it, also set the service as provider in app.module and also in listcomponent as provider.

The Service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { posts, users } from '../api.actions';
import { ListComponent } from '../list/list.component';

@Injectable({
  providedIn: 'root',

})

export class ApiCallService {
  // constructor(public getId: ListComponent)

  public getUsers() {
    return this.http.get<users[]>('https://jsonplaceholder.typicode.com/users');
  }
  public getPosts()
  {
    return this.http.get<posts[]>('https://jsonplaceholder.typicode.com/posts');

  }

  public test()
  {
    let id = 0;
    this.getId.SendID(id);
    this.getId.SendID(id)
    console.log(id);

  }
  constructor(private http: HttpClient, private getId: ListComponent ) {

  }

}

The App.Module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule } from '@ngrx/store';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { ListComponent } from './list/list.component';
import { userReducer } from './api.reducer';
import { EffectsModule } from '@ngrx/effects';
import { ApiEffects } from './api.effect';
import { ApiCallService } from './ApiCall/api-call.service';


@NgModule({
  declarations: [
    AppComponent,
    ListComponent,


  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    StoreModule.forRoot({rootValue: userReducer}),
    StoreDevtoolsModule.instrument({maxAge: 25, logOnly: environment.production, autoPause: true}),
    EffectsModule.forRoot([ApiEffects])
  ],
  providers: [ApiCallService],
  bootstrap: [AppComponent]
})
export class AppModule { };

The listComponent:

import { Component, Input, OnInit } from '@angular/core';
import { ApiCallService } from '../ApiCall/api-call.service';
import { Observable, map, BehaviorSubject, Subject } from 'rxjs';
import { Store } from '@ngrx/store'
import { RootState } from '../api.reducer';


@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css'],
  providers: [ApiCallService]
})
export class ListComponent implements OnInit {


  constructor(private api: ApiCallService, private store: Store<{rootValue: RootState}>) { }

  users = [];
  Uid:number = 0;
  UId$ = new Subject<number>();

  //Used To display the users and posts in HTML file
  users$ = this.store.select('rootValue').pipe(map(data => data.users));
  posts$ = this.store.select('rootValue').pipe(map(data => data.posts));

  //gets triggered when SingleUser is clicked
  UserClicked(userId:number)
  {
    this.Uid = userId;
    this.SendID(this.Uid);

  }

  //Sends data to Service 
  SendID(userId:number)
  {
    this.UId$.next(userId);
  }

  //Function from Service
  Test()
  {
    this.api.test();
  }

  ngOnInit(): void {
  }

}

There's a lot of code, so you'll only need to look for the providers.

I expected it to work, since i set it as provider in both ways and also didn't even put any code in the service function there.

addy
  • 3
  • 3
  • why do you need to inject the component inside the service ? In Angular Only services can be provided and injected. – Cheikh HAIBALA Jan 10 '23 at 15:10
  • I wanted to get data to the service from the component – addy Jan 10 '23 at 15:16
  • you can define a subject inside the service, subscribe to it inside the service and emit data from the component every time you need to have it in the service. This is usually how we communicate from components to services. you can see here : https://stackoverflow.com/questions/44066905/angular-2-send-data-from-component-to-service – Cheikh HAIBALA Jan 10 '23 at 15:18
  • Can you please share the code instead pictures. Also please share the app.module file. – Bozhinovski Jan 10 '23 at 15:28
  • Sharing code inside code blocks instead of images would make this question much more accessible. – Scollier Jan 10 '23 at 16:28
  • @CheikhHAIBALA that's why i added an observable in the listcomponent and passed the value with .next() – addy Jan 11 '23 at 08:47
  • @addy, You should re-thinking your app. You can **not** inject a component in your service. In general the services are "providedIn:root" (or in a module) so exists along all the life of the app. A component only exist if it's visible. A service generally call the API and return Observables. It's in component where you subscribe to this observables. If you want "communicate" a component with a service, you can use another service and and use some closer when we communicate two components using a service -really I can not imagine a situation it's neccessary- – Eliseo Jan 11 '23 at 09:11
  • @Eliseo thanks for your help. The thing is i wanted to get a value from the component to the service to change the url of the api-call, because you can also get from the api only specific details, in this example display all posts of the user with the same id. Thought it work if i just add it in the constructor to call the function. – addy Jan 11 '23 at 09:17
  • Then pass from the component to the service the id or the url. If you define in your service two variables "url" and "id", you can, from component write:`this.api.url="..."` or `this.api.callAnApi(this.id)`, Even you can to have a function in service `setConfig` and use again from component, some like `this.api.setConfig({url:...,id:...}` – Eliseo Jan 11 '23 at 09:41
  • Thank you! That worked for me. Sometimes the solution to it is so easy, just made it way harder than it had to be. – addy Jan 11 '23 at 09:57

1 Answers1

0

Remove component from service's constructor like this:

export class ApiCallService {
...
   constructor(private http:HttpClient) {}
...
}
Tyzia
  • 116
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Ronald Haan Jan 11 '23 at 07:39