我是Angular和JHipster的新手。请帮助解决问题。我没有在那里更改代码。有jhipster的默认登录代码。
堆栈跟踪:
TypeError:this.accountService未定义 堆栈跟踪: LoginService.prototype.logout@webpack-internal:///./src/main/webapp/app/core/login/login.service.ts:33:9 NavbarComponent.prototype.logout@webpack-internal:///./src/main/webapp/app/layouts/navbar/navbar.component.ts:49:9 View_NavbarComponent_30 / <@ng:///NgrkAppModule/NavbarComponent.ngfactory.js:1470:23
core / login / login.service.ts:
import { AccountService } from 'app/core/auth/account.service';
--------------------------------------------------
constructor(private accountService: AccountService)
--------------------------------------------------
login(credentials, callback?) {
const cb = callback || function() {};
return new Promise((resolve, reject) => {
this.authServerProvider.login(credentials).subscribe(
data => {
this.accountService.identity(true).then(account => {
resolve(data);
});
return cb();
},
err => {
this.logout();
reject(err);
return cb(err);
}
);
});
}
logout() {
this.authServerProvider.logout().subscribe();
this.accountService.authenticate(null);
}
core / auth / account.service.ts:
export class AccountService {
--------------------------------
authenticate() {
some code;
}
identity() {
some code;
}
--------------------------------
}
答案 0 :(得分:0)
如果this
处理不当,则从undefined
中读取某些内容并将其确定为this
是一个常见问题。
快速解决方案是将logout
用于an arrow:
logout = () => {
为了将来的安全起见,也可能在其他地方(例如login
)使用它。
答案 1 :(得分:0)
您可以在Promise之外保留此内容的引用,并代替它使用。
login(credentials, callback?) {
let that = this;
const cb = callback || function() {};
return new Promise((resolve, reject) => {
that.authServerProvider.login(credentials).subscribe(
data => {
that.accountService.identity(true).then(account => {
resolve(data);
});
return cb();
},
err => {
that.logout();
reject(err);
return cb(err);
}
);
});
}
还将@Injectable()添加到您的AccountService类中
@Injectable()
export class AccountService