Angular 如何在promise解析后返回值?
我正在使用Angular和Typescript进行验证,当我将值插入SQL数据库时,它会检查该值是否已经在数据库表中。我从ASP.NET核心API得到一个响应,如果该值已经在表中,数据库服务器将返回true 答案是:Angular 如何在promise解析后返回值?,angular,typescript,asynchronous,promise,async-await,Angular,Typescript,Asynchronous,Promise,Async Await,我正在使用Angular和Typescript进行验证,当我将值插入SQL数据库时,它会检查该值是否已经在数据库表中。我从ASP.NET核心API得到一个响应,如果该值已经在表中,数据库服务器将返回true 答案是: true 例如,我在数据库表中已经有值“1”,然后我尝试插入值“1”,但它会将其插入表中,当我再次尝试插入该值时,它将停止并不允许我插入该值。如果我刷新页面,即使数据库表中有>10个值为“1”,也会发生相同的过程。我可以使用什么来解决此问题?如何解决 FileCount:bool
true
例如,我在数据库表中已经有值“1”,然后我尝试插入值“1”,但它会将其插入表中,当我再次尝试插入该值时,它将停止并不允许我插入该值。如果我刷新页面,即使数据库表中有>10个值为“1”,也会发生相同的过程。我可以使用什么来解决此问题?如何解决
FileCount:boolean;
出现此问题的原因是,对this.getFileCount()方法的调用是异步运行的,也就是说,它不会等待响应,进程将继续,因此您必须等待响应 试试这个:
getFileCount() {
return this.http.get<boolean>(this.BaseURL + '/Count/File?Name=' + this.formData.Name);
}
insertRecord(form: NgForm) {
this.getFileCount().subscribe(result => {
this.FileCount = result;
console.log(this.FileCount);
if (this.FileCount == true) {
this.toastr.warning('Submitted failed', 'There is another file with the name: "' + this.formData.Name + '"');
}
else {
this.postFile().subscribe(
res => {
this.toastr.success('Submitted successfully', 'File Creation Complete');
this.refreshList();
},
(err) => {
console.log(err);
}
);
}
});
}
getFileCount(){
返回this.http.get(this.BaseURL+'/Count/File?Name='+this.formData.Name);
}
插入记录(格式:NgForm){
this.getFileCount().subscribe(结果=>{
this.FileCount=结果;
console.log(this.FileCount);
if(this.FileCount==true){
this.toastr.warning('Submitted failed','有另一个文件名为:“'+this.formData.name+'”);
}
否则{
此.postFile().subscribe(
res=>{
this.toastr.success('提交成功','文件创建完成');
这个.refreshList();
},
(错误)=>{
控制台日志(err);
}
);
}
});
}
@MuhammedAlbarmavi您的解决方案与我的完全相同,它是复制粘贴。检查您的解决方案。getFileCount确实返回了一个可观察值。起初,您试图通过使用async await来解决这个问题,这就是为什么我使用另一种方法@MuhammedAlbarmavi不,我提出了两种解决方案,Eduard使用了第二种。这就是为什么我删除了另一个,但我相信它是有效的。也许我看不到,别担心,我会删除我的,我们不需要在将来试图解决其他人的问题时混淆其他人
insertRecord(form: NgForm) {
this.getFileCount();
if (this.FileCount == true) {
this.toastr.warning('Submitted failed', 'There is another file with the name: "' + this.formData.Name + '"');
}
else {
this.postFile().subscribe(
res => {
this.toastr.success('Submitted successfully', 'File Creation Complete');
this.refreshList();
},
(err) => {
console.log(err);
}
);
}
}
postFile() {
return this.http.post(this.BaseURL + '/File', this.formData);
}
getFileCount() {
return this.http.get<boolean>(this.BaseURL + '/Count/File?Name=' + this.formData.Name);
}
insertRecord(form: NgForm) {
this.getFileCount().subscribe(result => {
this.FileCount = result;
console.log(this.FileCount);
if (this.FileCount == true) {
this.toastr.warning('Submitted failed', 'There is another file with the name: "' + this.formData.Name + '"');
}
else {
this.postFile().subscribe(
res => {
this.toastr.success('Submitted successfully', 'File Creation Complete');
this.refreshList();
},
(err) => {
console.log(err);
}
);
}
});
}