kaaai3
kaaai3

Reputation: 39

Angular2 http get data to localstorage doesn't work

I started working on angular 2 recently and i am trying out the http part right now, but I have some problems.

When I click the button to activate the function the http.get will send a key a username and a password to the api i made in php.

the http receives the details(this part works) and is suppose to store the data in localstorage but this doesn't work it only works when i click a second time.

What am i doing wrong?

HTML

<input type="text" [(ngModel)]="username" /><br>
<input type="text" [(ngModel)]="password" /><br>
<button (click)="checkLogin()">set</button>

Angular2 function

checkLogin() {
    let url = 'http://localhost:82/api/getData.php?key=' + this.key + '&username=' + this.username + '&password=' + this.password;
        this.http.get(url)
        .subscribe(res => this.userData = res.json());

    let jsonId = this.userData['id'];
    let jsonUsername = this.userData['username'];

    localStorage.setItem('id', jsonId);
    localStorage.setItem('username', jsonUsername);

    // error handling
    let jsonError = this.userData['error'];

    localStorage.setItem('error', jsonError);
}

Upvotes: 0

Views: 582

Answers (1)

mickdev
mickdev

Reputation: 2885

You should make sure that your receive the desired response before setting it. Try something like this :

checkLogin() {
    let url = 'http://localhost:82/api/getData.php?key=' + this.key + '&username=' + this.username + '&password=' + this.password;
        this.http.get(url)
        .subscribe(res => {
            this.userData = res.json();

            //for readability you should export this part in a local function
            let jsonId = this.userData['id'];
            let jsonUsername = this.userData['username'];

            localStorage.setItem('id', jsonId);
            localStorage.setItem('username', jsonUsername);

            // error handling
            let jsonError = this.userData['error'];

            localStorage.setItem('error', jsonError);
        });
}

Upvotes: 1

Related Questions