调用接收凭据并检索用户的 Rest 服务。HTTP 方法正在正常执行,但 User 对象未更新,我无法将其绑定到视图:
用户服务(连接到休息服务):
@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'));
};
}
查看 TS(持有 User 对象、凭据并调用服务):
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 from
service 1" + JSON.stringify(response))},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
console.log("Response from service 2" + JSON.stringify(this.user));
}
HTML模板:
Username: <input type="text" [(ngModel)]="credentials.username" name="login"> <br>
Password: <input type="text" [(ngModel)]="credentials.password" name="password" > <br>
{{user.username}} // <--- THIS 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()
{
}
}
凭证模型
export class Credentials
{
username:string;
password:string;
constructor()
{
}
}
安慰
Angular 在开发模式下运行。调用 enableProdMode() 以启用生产模式。login.component.ts:33 服务 2 的响应{} login.component.ts:29 服务 1 的响应{"name":"edgargdl","lastname":"flores","password":"password"," email":"[email protected]","phone":"2107847131","contactPreference":null,"username":"edgargdl","links":[]} login.component.ts:31 订阅是完全的
不是您正在使用的语法的忠实粉丝,您可以尝试一次。
this.userService.loginService(this.credentials).subscribe(
(response) => this.user = response,
(error) => console.log("Error happened" + error),
() => console.log("the subscription is completed"));
您正在使用无法访问function()
引用的语法。this
尝试使用 lambda 的
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句