我有一个父类HTTPConnection
,我希望将其用作网络工具类以减少代码重复,但当我尝试使用它时,core.umd.js
说Uncaught ReferenceError: HTTPConnection is not defined
但是它定义让我感到困惑。
我的HTTPConnection
课程:
import {Response, RequestOptionsArgs, Headers} from "@angular/http";
import {Observable} from "rxjs/Observable";
export class HTTPConnection {
protected static addAuthorizationHeader(token: string, reqOptionsArgs?: RequestOptionsArgs): RequestOptionsArgs {
if (reqOptionsArgs) {
reqOptionsArgs.headers.append('Authorization', token);
return reqOptionsArgs;
}
var headers = new Headers();
headers.append('Authorization', token);
return {headers: headers};
}
//Copied from the Angular 2 Developer Guide - HTTP Client
protected static extractData(res: Response) {
return res.json || {};
}
protected static handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = "Error: " + (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
扩展它的服务:
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Http, Response} from "@angular/http";
import {HTTPConnection} from "./http.connection";
import 'rxjs/add/operator/map';
@Injectable()
export class CoursesService extends HTTPConnection {
private token: string = "pew";
constructor(private _http: Http) {
super();
}
getCourses(): Observable<Response> {
return this._http.get('https://httpbin.org/get', HTTPConnection.addAuthorizationHeader(this.token))
.map(HTTPConnection.extractData)
.catch(HTTPConnection.handleError);
}
}
如果有人能帮助我,我真的很感激
答案 0 :(得分:0)
原来这是一些奇怪的编译错误(不确定TypeScript或Angular 2错误),其中一个类仍然引用了HTTPConnection
,即使它没有被使用。< / p>