angular - Angular2 first response to POST request undefined -
i have simple method makes post request
postdata(){ var headers = new headers(); headers.append('content-type', 'application/json'); var json = json.stringify({email: 'admin', password: 'admin'}); return this._http.post('http://localhost:8080/addressbook_rest/api/v1/contacts/login', json , {headers: headers}); }
then component call above method
onlogin() { this._service.postdata().map(res => res.json()).subscribe( data => { this.loggedin = data }, err => { console.log(err); } ); console.log(this.loggedin); }
the problem on first call, variable this.loggedin undefined after want( this.loggedin=true). don't know why gets second time.
in fact, it's because request handled asynchronously. means console.log(this.loggedin);
return undefined first time because it's outside subscribe callback. it's executed before receiving request response.
you should use that:
onlogin() { this._service.postdata().map(res => res.json()).subscribe( data => { this.loggedin = data; console.log(this.loggedin); // <------- }, err => { console.log(err); } ); }
Comments
Post a Comment