Angular 5 synchronous HTTP call

前端 未结 3 347
失恋的感觉
失恋的感觉 2021-01-04 03:34

I have an Angular 5 application in which I have to call some heavy REST service (usually takes some seconds). I need its result in different part of application, so I would

相关标签:
3条回答
  • 2021-01-04 03:48

    Try using await/async

    async getResult(): Promise<MyCustomObject> {
        if (typeof this.result === 'undefined') 
        {
            // save result
            this.result = await this.service.call()
            .toPromise()
            .then(resp =>resp as MyCustomObject);//Do you own cast here
    
        }
        return this.result;
    }
    
    0 讨论(0)
  • 2021-01-04 03:58

    I upvoted the response of David above, but I think there may be a design flaw. You should actually not save (in local storage) the result in the getResult function. It's a side effect and it might be undesirable at some point and render your getResult hardly reusable in case you just want to get without save.

    Also having the this.result === 'undefined' might create problem as well if you want to refresh the data.

    So if you want to get these results in the ngOnInit, you could do it like that:

    ngOnInit() {
        if (typeof this.result === 'undefined') {
            this.getResult().then(result => {
                // save the result here
                this.result = result;
    
                // save in local storage ...
            });
        }
    }
    
    getResult(): Promise<MyCustomObject> {
        return this.service.call().toPromise();
    }
    

    Note that you cannot await in ngOnInit. But now your getResult() function is reusable in many other cases.

    0 讨论(0)
  • 2021-01-04 04:05

    The question is how I can wait until HTTP request is finished and then save and return the 're sult' object.

    // Code in service:

    ServiceMethod:Observabke<any>(){
         if (typeof this.result === 'undefined') {
                    return this.service.call().map(res=>res);
    }
    

    // This is code in component.

     componentMethod(){
    
    
            return this.service.ServiceMethod()
                .subscribe(response => {
                    this.result = response;
                   },
                   ()=>//handle error,
                   () => // call completed { return this.result;  // Subscriber});
        }
        return this.weeklyPlayer;  // MyCustomObject (This return won't wait for http to get completed. Not sure why you want multiple returns.)
    
        }
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题