json - Angular http post not working 1st time, but works on 2nd time -
trying first angular exercise. receiving undefined value on 1st time http post, 2nd time getting proper response (edge, firefox). thanks!
loginservice (calls http post method , returns observable)
login(loginrequest: loginrequest){ console.log("loginservice.login - username " + loginrequest.username); let options = new requestoptions({ headers: headers }); return this.http.post(this.http_url, loginrequest, options).map( res => res.json());
loginformcomponent (calls service class , convert json typescript object)
onsubmit() { this.loginsvc.login(this.loginrequest).subscribe( data => this.loginresponsestr = data, error => alert(error), () => console.log('request completed') ); var loginresponse = new loginresponse(); loginresponse.fillfromjson(json.stringify(this.loginresponsestr)); console.log(loginresponse.status); console.log(loginresponse.statusdesc); if(loginresponse.status == "success"){ this.router.navigate(['/home-page']); }
console log
loginservice.login - username admin main.bundle.js:370:9 undefined main.bundle.js:266:9 undefined main.bundle.js:267:9 request completed main.bundle.js:263:181 loginservice.login - username admin main.bundle.js:370:9 success main.bundle.js:266:9 valid user main.bundle.js:267:9 request completed main.bundle.js:263:181
angular server calls asynchronous, mean code wont wait server respond before executing rest of code. such php. not see blank page waiting server send data. when want deal respose come server call have add code within subscribe
; means if information needed passed service. code should this.
onsubmit() { this.loginsvc.login(this.loginrequest).subscribe( data => { this.loginresponsestr = data var loginresponse = new loginresponse(); loginresponse.fillfromjson(json.stringify(data)); console.log(loginresponse.status); console.log(loginresponse.statusdesc); if (loginresponse.status == "success") { this.router.navigate(['/home-page']); } }, error => alert(error), () => console.log('request completed') ); }
Comments
Post a Comment