繁体   English   中英

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

[英]How to instantiate an angular 2 service without using the constructor?


我正在尝试在另一个类中使用我的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.
         });
    }



}

您没有在组件中注入服务

您的UploadAdapter构造函数应如下所示

constructor(private http: ApiService) {}

另外你需要使用

this.http.post

代替

http.post

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM