試圖學習一些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。抱歉。這是一個錯字!現在糾正 –