subscribe not returning value immediately.

6 views
Skip to first unread message

Arun Kumar

unread,
Aug 23, 2017, 11:15:14 PM8/23/17
to Angular and AngularJS discussion
I am new to Angular, trying to read server side controller cookies in my typescript file. Below is my code. 
I am able read cookies successfully. But i am getting the results after a while not immediately. I want set username value in ngOnInit function..
 

public ngOnInit() {
        
      this.getAuthentication(); //want get value after this statement.
     console.log(this.userName); //returns undefined.

---- if(this.userName !=null)
{
this.loadUserInformation(this.userName);
}

console.log(this.userName); //returns value.

}

    public getAuthentication()
    {
        let user = new User();
        
        this.userService.AuthenticateUser(user)
            .subscribe(
            response => this.validateUserOnSuccess(response),
            response => this.validateUserOnError(response)
        );
    }

public validateUserOnSuccess(response: User) {
        //this.userObj = response;
        this.userName = response.UserName;
        //console.log(this.userName);
     }

Sander Elias

unread,
Aug 24, 2017, 6:11:12 AM8/24/17
to Angular and AngularJS discussion
Hi Arun,

You should read some stuff about how asynchrony works in JS. Learn about promises and observables and callbacks. You should really understand how promises work before you try stuff like this. For http calls, the observables mimic this behaviour very close. 
Don't ever subscribe to an observable inside a service, unless you really know what you are doing. Once you have this down, this is how you could program your onint once everything else is in place too:

class someElement {
    constructor
(private userService: UserService) {}

    async ngOnInit
() {
       
this.user = await this.userService.getAuthentication.toPromise();
        console
.log(this.user)
   
}
}

But first, make sure you are understanding how callbacks and promises work.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages