'How to prevent any execution until got response from server in Angular?
I am very new to Angular and my requirements are like below.
A is a function in Service which returns true or false
B is a function in Component which excepts a values from service.
function A()
{
isSuccess: boolean = false;
//logic
if (err)
{
this.isSuccess = false;
}
else
{
this.isSuccess = true;
}
return this.isSuccess;
}
function B()
{
var obj = new Service();
var ret=obj.A();
}
here value of "ret" in function B is always false. It is because it return false from function A before we receive response from server.
Actual Example
upload.service.ts
export class S3FileUploadService
{
isSuccess: boolean = false;
constructor(private http: HttpClient) { }
uploadFile(file: File, bucketName: string, fileName: string): boolean
{
debugger;
const contentType = file.type;
const bucket = new S3(
{
accessKeyId: '<accessKeyId>',
secretAccessKey: '<secretAccessKey>',
region: '<region>'
});
const params = {
Bucket: bucketName,
Key: fileName,
Body: file,
ContentType: contentType};
bucket.putObject(params, function (err: any, data: any) {
if (err)
{
this.isSuccess = false;
}
else
{
this.isSuccess = true;
}
});
return this.isSuccess;
}
}
upload.component.ts
var isSucess=this.uploadService.uploadFile(file, this.bucket, file.name);
if(isSucess){
//further logic of component
}
Here before call back function get executed it returns false to component. But after 3 to 4 second it goes into call back function and set it to true. But it was too late because component logic already got executed.
I have also used promise() and then(). but no luck.
Update
tried with promise
service
in same function i used putObject method like below
return await bucket.putObject(params).promise()
component
this.uploadService.asynchUploadFile(file, this.bucket, file.name).then((data) => {
if (!data.$response.error) {
this.IsSuccess=true
}
else
this.IsSuccess=false
})
Solution 1:[1]
@Aijaz here is a working demo that illustrates a very similar scenario. Based on Observables: https://angular-ivy-dgzmep.stackblitz.io.
The service provides this functionality that demonstrates a lengthy API call:
getWithSuccess(): Observable<boolean> {
return of(true).pipe(delay(3000));
}
The component calls this service as follows:
this.success$ = this.myService.getWithSuccess();
this.success$
.pipe(tap(response => console.log(response)))
.subscribe();
Same for failure so you can see both scenarios.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Benny |
