0


I'm trying to use my ApiService class (handling api requests) in another class, but can't get it to work.
The issue is the ApiService constructor needs HttpClient, that means I can't just use something like: http = new ApiService(new HttpClient(), globals)

ApiService:

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest } from '@angular/common/http';
import { Globals } from './globals';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient, private globals: Globals) {}

  get(url : string, params: {}){
    return this.http.get(this.globals.api_url.concat(url), {params: params});
  }

  ...
}

Class calling ApiService:

export class UploadAdapter {
    http: ApiService;
    constructor() {}

    upload() {
           //Here I get an error saying can't get post of undefined 
       http.post('api_url'.concat('/medias/upload'), {}, {})
         .subscribe((data) => {
            //do stuff here.
         });
    }



}

1 Answers1

1

You are not injecting the service in your component

Your UploadAdapter constructor should be like this

constructor(private http: ApiService) {}

Also you need to use

this.http.post

Instead of

http.post

asimhashmi
  • 4,258
  • 1
  • 14
  • 34
  • Hi Asim, The thing is UploadAdapter isn't a component just another service itself to handle communication with the api. I can't inject the ApiService in the constructor of UploadAdapter, otherwise when instantiating it I need use something in the line of: new UploadAdapter(new ApiService(new HttpClient, new Globals ())) – Soufiane Sakhi May 06 '19 at 20:16