Angular2绑定不能用于Observable

时间:2017-08-20 19:00:50

标签: angular observable

调用接收凭据并检索用户的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(保留用户对象,凭据并调用服务):

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的响应{&#34;名称&#34;:&#34; edgargdl&#34;,&#34;姓氏&#34;:&#34; flores&#34;,&# 34;密码&#34;:&#34;密码&#34;&#34;电子邮件&#34;:&#34; edgargdl@hotmail.com",&#34;电话&#34;:&#34 ; 2107847131&#34;&#34; contactPreference&#34;:空,&#34;用户名&#34;:&#34; edgargdl&#34;&#34;链接&#34;:[]} login.component.ts:31订阅完成

1 个答案:

答案 0 :(得分:0)

您使用的语法不是非常忠实的粉丝,可以尝试一次。

  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&#39;