【发布时间】:2017-07-26 23:08:59
【问题描述】:
在做我们的第一个大型应用程序时,我们遇到了一个应该在 typescript 2.0+ 中修复的问题
拥有抽象类:
export abstract class HttpBaseService {
protected abstract readonly TAG: any;
protected abstract _state: GlobalState;
private r = Math.random();
protected extractData(res: Response) {
console.log(`${this.TAG}:extractData:`, res.json());
const data = res.json() || [];
return data;
}
protected handleErrors(error: Response) {
console.error(`${this.TAG}:handleErrors:`, error);
console.log(this.TAG);
console.log(this._state);
if (error.status === 401 || error.status === 403) {// Not Authorized
console.error(`${this.TAG}:handleErrors: NOT AUTHORIZED`, error);
this._state.notifyDataChanged("logout", error);
}
return Observable.throw(error.json());
}
}
和实施:
@Injectable()
export class AlbumService extends HttpBaseService {
TAG = AlbumService.name;
constructor(protected _state: GlobalState,
private http: Http,
private auth: AuthService,
private localStorage: LocalStorageService,) {
super();
this._state = _state;
}
albums() {
console.log(`${this.TAG}:albums:`);
console.log(this._state);
const ALBUMS_URL = this.albumsUrl();
const token = this.auth.getToken();
const headers = new Headers();
headers.append('Authorization', `Token ${token}`);
return this.http
.get(`${Constants.API_URL}${ALBUMS_URL}`, {headers})
.catch(this.handleErrors)
.map(this.extractData);
}
}
当父类中的函数handleError在子类中执行时,参数TAG和_state都为“未定义”
请注意,我已经对其进行了测试,从构造函数中将其抽象、受保护、公开,手动分配成员,也许还有其他几个。
我必须遗漏一些东西,因为在子类构造函数中,我尝试在分配 _state 后调用 handleError 方法,它按预期工作,具有 TAG 的值和 _state 的值。
更新:将问题降至最低
现在我有:
export abstract class HttpBaseService {
protected abstract _state: GlobalState;
protected handleErrors(error: Response) {
console.log(this._state);
}
protected extractData(res: Response) {
const data = res.json() || [];
return data;
}
}
和实施:
@Injectable()
export class AlbumService extends HttpBaseService {
constructor(_state: GlobalState,
private http: Http,
private auth: AuthService,
private localStorage: LocalStorageService,) {
super();
this._state = _state;
}
albums() {
const token = this.auth.getToken();
const headers = new Headers();
headers.append('Authorization', `Token ${token}`);
return this.http
.get(`${Constants.API_URL}`, {headers})
.catch(this.handleErrors)
.map(this.extractData);
}
}
【问题讨论】:
-
我不知道这是否与您遇到的问题有关,但
this._state = this._state;看起来多余 - 应该是this._state = _state;吗? -
@0mpurdy 这是我尝试的实现之一的错误
-
已经试过不做抽象类了,不行
-
我尝试了其他 9 种解决方案,包括非抽象扩展、超类中的构造函数、子类的构造函数中的赋值
-
您是否尝试过将大部分代码删除到最低限度以重现问题?这将使回答更容易,并且在此过程中您可能会解决自己的问题! minimal reproducible example
标签: angular typescript