我正在使用扩展的HttpClass,以便我可以动态应用标头和url路径。这就是它的样子:
app.http.ts
export enum Type {
PREAUTH = 0,
AUTH = 1,
PRINTER = 2,
TERMINAL = 3
}
@Injectable()
export class AppHttp extends Http {
private typesOn: Array<any> = [false, false, false, false];
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
this.presetPetition(Type.AUTH);
}
presetPetition(type: number) {
this.typesOn.forEach(t => (t = false));
this.typesOn[type] = true;
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return super.get(this.updateUrl(url), this.getRequestOptionArgs(options));
}
private updateUrl(req: string) {
if (this.typesOn[Type.AUTH]) {
return environment.apiURL + req
} else {
return req
}
}
app.module.ts
providers: [
AppHttp,
{
provide: Http,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions]
}
]
http.factory.ts
export function httpFactory(xhrBackend: XHRBackend, requestOptions:
RequestOptions): Http {
return new AppHttp(xhrBackend, requestOptions);
}
当我尝试更改http请求的类型时,我将AppHttp导入组件/服务,并在我的http请求之前调用 presetPetition()。
我得到No Provider for Backend Connection
。
所以我理解不能进行冗余的提供程序导入(Http和AppHttp),这必定是错误。
如何在扩展类中访问公共函数?或者我的方法是错的?
答案 0 :(得分:1)
这违反了角度的编码标准。仅为URL集和crud操作创建API服务,并且为身份验证扩展HTTP服务。
对于常见的API:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class BaseService {
private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
private options = new RequestOptions({ headers: this.headers });
constructor(private http: Http) { }
// Get all
getAll(url: any): Observable<any> {
return this.http.get(url).map(res => res.json());
}
// Count all
count(url: any): Observable<any> {
return this.http.get(url).map(res => res.json());
}
// add
add(url: any, entity: any): Observable<any> {
return this.http.post(url, JSON.stringify(entity), this.options);
}
// Get by id
getById(url: any, entity: any): Observable<any> {
return this.http.get(url + `/${entity._id}`).map(res => res.json());
}
// Update by id
editById(url: any, entity: any): Observable<any> {
return this.http.put(url + `/${entity._id}`, JSON.stringify(entity), this.options);
}
// Delete by id
deleteById(url: any, entity: any): Observable<any> {
return this.http.delete(url + `/${entity._id}`, this.options);
}
}
https://github.com/mdshohelrana/mean-stack/blob/master/client/app/shared/services/base.service.ts
对于扩展HTTP服务:
http://www.adonespitogo.com/articles/angular-2-extending-http-provider/
我认为这会对你有所帮助。