以下是导致错误的代码
@Injectable({ providedIn: "root" })
export class AuthService {
.....
....
addUser(){
this.http.post<any>(API_ENDPOINT, postData)
.subscribe(
//response when success
this.registerDone,
//error
(err) => {
console.log(err);
this.authStatusListener.next(false);
}
);
}
private registerDone(res:any){
this.clearAuthData();
....
....
}
private clearAuthData() {
localStorage.removeItem("userInfo");
}
}
core.js:15723 ERROR TypeError: this.clearAuthData is not a function
at SafeSubscriber.push../src/app/auth/auth.service.ts.AuthService.registerDone [as _next] (auth.service.ts:193)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:134)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:84)
一个丑陋的解决方法是将registerDone功能块的所有内容放入(res)=> {} OR
因为我将在其他成功的响应功能中重用 registerDone(res:any)。最好以简洁明了的方式使用此函数,而不是在每个块内重新声明。
已编辑:(res)=> {registerDone(res)}有效,但不确定使用registerDone作为输入函数有什么区别,因为它也接受一个参数作为函数。
答案 0 :(得分:0)
尝试一下
export class AuthService {
.....
....
addUser(){
this.http.post<any>(API_ENDPOINT, postData)
.subscribe(
//response when success
() => this.registerDone(),
//error
(err) => {
console.log(err);
this.authStatusListener.next(false);
}
);
}
private registerDone(res:any){
this.clearAuthData();
....
....
}
private clearAuthData() {
localStorage.removeItem("userInfo");
}
}
非箭头函数将this
绑定到将实际执行该函数的上下文,即不在您的AuthService中 ,而箭头函数会将this
绑定到当前AuthService的实例。检查here了解更多详细信息。