如何在不使用构造函数的情况下实例化angular 2服务?

时间:2019-05-05 20:23:52

标签: angular typescript


我正在尝试在另一个类中使用我的ApiService类(处理api请求),但无法使其正常工作。
问题在于ApiService构造函数需要HttpClient,这意味着我不能只使用以下内容: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});
  }

  ...
}

类调用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 个答案:

答案 0 :(得分:1)

您没有将服务注入您的组件中

您的UploadAdapter构造函数应该像这样

constructor(private http: ApiService) {}

还需要使用

this.http.post

代替

http.post