简体   繁体   中英

Angular 2 Rxjs creating action after server response

I am a new in Angular2(and especially to RxJs library) and stacked on next step. My web site starts with a register page. And after the completion of of register form i have base service.auth.ts method register usage

     registerUser(){
        this.authService.registerUser(this.registrationForm.value)
        .subscribe((data) => {
           console.log(data);
        })
        //this line should apear after server response from backend
        console.log('AFTER SERVER RESPONSE')
        }

And i recieve response like this

在此处输入图片说明

I read some stuff about flatMap method in RxJs documentation and it is claimed to be alternative to default Promise method then() - but i failed to create working instance of code that acutally implements flatMap method for my case

So the question is : How can i achieve result so 'AFTER SERVER RESPONSE' message appears AFTER server response? (not before as mentioned on previous screenshot)

You should wait for asynchronous task to complete. Move that console.log('AFTER SERVER RESPONSE') inside your subscribe block.

registerUser() {
        this.authService.registerUser(this.registrationForm.value)
        .subscribe((data) => {
           console.log(data);
           //this line should apear after server response from backend
           console.log('AFTER SERVER RESPONSE')
        });

      // anything written over here will execute before `registerUser()` returns data
     console.log('THIS WILL PRINT BEFORE SERVER RESPONSE')
}

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