angular - Angular2 Binding not working on Observable -
calling rest service receives credentials , retrieves user. http method being executed fine, user object not being updated , can not bind view:
user service (connects rest service):
@injectable() export class userservice { constructor(private http:http) { } public loginservice(credential:credentials):observable<user> { let headers = new headers({ 'content-type': 'application/json' }); let options = new requestoptions({ headers: headers }); return this.http.post ("http://localhost:8090/users/"+credential.username, json.stringify(credential),options) .map((res) => res.json().user) .catch((error:any) => observable.throw(error.json().error || 'server error')); }; }
view ts (holds user object, credentials , calls service):
export class logincomponent { credentials = new credentials(); private user: user; private anyerrors: boolean; private finished: boolean; constructor(private userservice: userservice) { } login(){ this.userservice.loginservice(this.credentials).subscribe( function(response) {this.user = response ; console.log("response service 1" + json.stringify(response))}, function(error) { console.log("error happened" + error)}, function() { console.log("the subscription completed")} ); console.log("response service 2" + json.stringify(this.user));
}
html template:
username: <input type="text" [(ngmodel)]="credentials.username" name="login"> <br> password: <input type="text" [(ngmodel)]="credentials.password" name="password" > <br> {{user.username}} // <--- not being updated when click login <button (click)="login()">login</button> --------------------------------------------- user model: export class user { name:string; lastname:string; address2:string; email:string; phone:string; username:string; password:string; constructor() { } }
credential model
export class credentials { username:string; password:string; constructor() { } }
console
angular running in development mode. call enableprodmode() enable production mode. login.component.ts:33 response service 2{} login.component.ts:29 response service 1{"name":"edgargdl","lastname":"flores","password":"password","email":"edgargdl@hotmail.com","phone":"2107847131","contactpreference":null,"username":"edgargdl","links":[]} login.component.ts:31 subscription completed
not great fan of syntax using can try once.
this.userservice.loginservice(this.credentials).subscribe( (response) => this.user = response, (error) => console.log("error happened" + error), () => console.log("the subscription completed"));
you using function()
syntax reference this
not accessible .try using lambda's
Comments
Post a Comment