英文:
Promise with Angular is not assignable to type ts2322
问题
I'm trying to do a login in Angular, but I get the error with the promises.
login(user?: string, password?: string): Promise<ApiResponse<User>> {
return new Promise((resolve) => {
let promise: Promise<ApiResponse<UserLogged>>;
if (user && password) // I'm logging in
promise = this.http.post<ApiResponse<UserLogged>>(this.baseUrl + "login", { user: user, password: password }).toPromise();
else // Check if I already have an active session on the server
promise = this.http.get<ApiResponse<UserLogged>>(this.baseUrl + "login").toPromise();
// Process the response
});
}
apiresponse.ts
export interface ApiResponse<T> extends BaseDTO {
status: number;
message?: string;
data?: T
}
baseDTO
export interface BaseDTO {
}
Can someone explain to me what I am doing wrong.
Sorry, my English is poor.
Thank you.
User
export interface User extends BaseIdDTO {
user: string;
password?: string;
mail: string;
name?: string;
}
Change in tsconfig.json the "strict: true" to "strict: false" and the error disappears.
英文:
I'm trying to do a login in Angular, but I get the error with the promises.
"Type 'Promise<ApiResponse<UserLogged> | undefined>' is not assignable to type 'Promise<ApiResponse<UserLogged>>'. ts2322
login(user?:string, password?:string):Promise<ApiResponse<User>> {
return new Promise((resolve) => {
let promise:Promise<ApiResponse<UserLogged>>;
if (user && password) //me estoy logueando
promise=this.http.post<ApiResponse<UserLogged>>(this.baseUrl + "login", {user: user, password: password}).toPromise();
else //valido si ya tengo sesion activa en el server
promise=this.http.get<ApiResponse<UserLogged>>(this.baseUrl + "login").toPromise();
//proceso respuesta
});
}
apiresponse.ts
export interface ApiResponse<T> extends BaseDTO{
status: number;
message?: string;
data?: T
}
baseDTO
export interface BaseDTO {
}
Can someone explain to me what I am doing wrong.
Sorry my English is poor
thank you
User
export interface User extends BaseIdDTO{
user:string;
password?:string;
mail:string;
name?:string
Change in tsconfig.json the "strict:true" to "strict: false" and the error disappears.
答案1
得分: 1
好的,我感谢你的建议,我是一个初学者,我会学习如何使用observable来做这件事。
英文:
ok, I thank you for your suggestions, I am a beginner, I will study how to do it with observable
答案2
得分: 0
开始时编写干净的代码?
login(user?: string, password?: string) {
if (user && password) return this.http.post(this.baseUrl + 'login', { user, password }).toPromise();
else return this.http.post(this.baseUrl + 'login').toPromise();
}
另外,你真的应该使用 observables,使用 promises 是一种降级。
英文:
Make clean code to start with ?
login(user?: string, password?: string) {
if (user && password) return this.http.post(this.baseUrl + 'login', { user, password }).toPromise();
else return this.http.post(this.baseUrl + 'login').toPromise();
}
Also, you should really use observables, using promises is a downgrade.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论