简体   繁体   中英

How to use Callback function on successful HTTP request in Angular2?

am getting the details from a service and assigning it to an loginDetailsArray array. now i need to call the functions() only after getting the data successful. i just tried to call functions() directly, but it is reading that function before getting the data. i was thinking about using call back function here. but as am new to this, i have no idea of how to get it. Thanks in advance.

 loadLoginDetails() { this.customerService.getLoginDetails().subscribe(res => { this.loginDetailsArray = res.json(); }); } functions() { var minLength = this.loginDetailsArray.rules.username.minlength; var maxLength = this.loginDetailsArray.rules.username.maxlength; var pattern = this.loginDetailsArray.rules.username.pattern; } 

This should just work?

loadLoginDetails() {

  this.customerService.getLoginDetails().subscribe(res => {
    this.loginDetailsArray = res.json();
    this.functions();
  });
}

When consuming your service, you get 3 responses, 1 for the data, 1 for the error & 1 for when the call is completed.

loadLoginDetails() {
    this.customerService.getLoginDetails().subscribe(
        res => {
            //Code if your response has data.
        },
        error => {
            //Code if your response has error.
        },
        () => {
            //Code when your request is finished.
        }
    );
}

You can either call your functions from the

res => {}

if you want it to run only if you had a successful response, if you want to run it regardless of your response, run it from

() => {}

Regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM