Angular2 Typescript 静态构造函数声明



我对静态类缺乏一些练习,因此无法正确初始化。我有以下课程:

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 未定义(控制台.log(,所以我假设初始化不正确。

欢迎任何帮助

如果你创建Utils类的新时刻,constructor将调用的类,另一方面,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
});  
}
}

如果你想使用Utils的静态方法,你必须在使用之前手动分配一个http对象

Utils.http = http; 

之后你可以使用它;

我看到您想对formData对象执行POST请求。您可以使用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
});  
}
}

最新更新