试图学习一些Angular 4,并得到了这个问题。打字稿,承诺和倍数回复类型
我有一个REST服务器(Spring Boot),它有一个端点来登录用户,如果登录成功,它将响应头部中的JWT标记,否则用401或500(if出现问题)。
因此,要检查登录,我用下面的代码(服务):
export const TOKEN_NAME = 'jwt_token';
const AUTH_HEADER_KEY = 'Authorization';
const AUTH_PREFIX = 'Bearer';
@Injectable()
export class AuthService {
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
constructor(private http: HttpClient) { }
login(username: string, password: string): Promise<boolean> | Promise<never>
{
const credentials = {
username: username,
password: password
};
const req = this.http.post(`http://localhost:8080/login`, credentials, { headers: this.headers, observe: 'response' });
return req.toPromise()
.then(r => this.processLoginResponse(r))
.catch(e => this.handleLoginError(e));
}
private processLoginResponse(res: HttpResponseBase): boolean {
if (res.header.has(AUTH_HEADER_KEY)) {
const authorizationHeaderValue = res.headers.get(AUTH_HEADER_KEY);
const regex = new RegExp(`^${AUTH_PREFIX} (.*)`);
const m = regex.exec(authorizationHeaderValue);
if (m !== undefined && m.length === 2) {
// TODO: store the token on localstorage
return true
}
}
return false;
}
private handleLoginError(error: HttpErrorResponse): boolean | Promise<never> {
if (error.status === 401) {
return false;
} else if (error.status === 403) {
// bad request
return Promise.reject(new Error('Bad request custom message'));
} else {
return Promise.reject(new Error('Something goes wrong!'));
}
}
}
所以,在我AuthService
,该login
方法可以返回一个布尔值(承诺)或错误。
然后,在我的组件,如果我尝试使用下面的代码:
const loginResult = this.authService.login('john_smith', 'secret123').then(r => { console.log(r); });
我得到了一个错误,用下面的内容:
TS2349:Cannot invoke an expression whose type lacks a call signature. Type '(<TResult1 = boolean, TResult2 = never>(onfulfilled?: (value: boolean) => TResult1 | PromiseLike<...' has no compatible call signatures.
。
没有意识如何纠正这一点。
难道这只是一个错字...'Promisse'(double-s)? –
Fenton
ops。抱歉。这是一个错字!现在纠正 –