Angular2 Typescript静态构造函数声明

时间:2018-07-06 11:11:27

标签: typescript angular5 static-classes

我在静态类上缺乏一些实践,因此,我无法正确初始化。我有以下课程:

import { HttpEvent, HttpClient, HttpRequest, HttpEventType } from '@angular/common/http';

export class Utils {

  static http: any;
  constructor(private http: HttpClient) {}

  static uploadMediaFile(file, api: string, model: any) {
    const formData = new FormData();
    formData.append(file.name, file);
    const uploadReq = new HttpRequest("POST", api, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
     //blah blah
    });  
  }
}

执行上述操作,返回:"ERROR TypeError: Cannot read property 'request' of undefined"

尝试调试,似乎http是undefined(console.log),所以我认为初始化不正确。

欢迎任何帮助

2 个答案:

答案 0 :(得分:1)

我看到您想对POST对象进行一个formData请求。您可以使用http.post代替request方法

并且无需使用static http: any。同样,您的方法不必是static

export class Utils {

  constructor(private http: HttpClient) {}

  uploadMediaFile(file, api: string, model: any) {
    const formData = new FormData();
    formData.append(file.name, file);
    const uploadReq = new HttpRequest("POST", api, formData, {
      reportProgress: true,
    });

    this.http.post(uploadReq).subscribe(event => {
     //blah blah
    });  
  }
}

答案 1 :(得分:1)

如果您创建constructor类的新实例,则将调用类Utils,另一方面,static(http)只是在声明时未分配值,为什么是Utils.http未定义。 我相信您可能会对角度依赖注入感到困惑,最好的情况是创建一个UtilsService注入http对象,而不是使用静态方法。

@Injectable()
export class UtilsService {

  constructor(private http: HttpClient) {}

  uploadMediaFile(file, api: string, model: any) {
    const formData = new FormData();
    formData.append(file.name, file);
    const uploadReq = new HttpRequest("POST", api, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
     //blah blah
    });  
  }
}

如果要使用实用程序的静态方法,则必须在使用前手动分配http对象

Utils.http = http; 

之后就可以使用它了