2017-08-20 19 views
0

資格情報を受け取り、ユーザーを取得するRestサービスを呼び出します。 HTTPメソッドが細かい実行されているが、ユーザーオブジェクトが更新されていないと私はビューにバインドすることはできません。Angular2バインディングがObservableで機能しない

ユーザーサービス(RESTサービスに接続):

@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() 
    { 

    } 
} 

コンソール

角度は、開発モードで実行されています。プロダクションモードを有効にするには、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サブスクリプションが完了しました

+0

を使用してアクセス.Tryないfunction()構文を使用していますか? –

+0

あなたは矢印関数ではなく関数を使用しており、正しく束縛していないので、 'this'はあなたの考えではありません。 – jonrsharpe

+0

ええ、それは私の問題だった、ありがとう –

答えて

0

あなたが使用しているシンタックスのファンではありません。

this.userService.loginService(this.credentials).subscribe(
    (response) => this.user = response, 
    (error) => console.log("Error happened" + error), 
() => console.log("the subscription is completed")); 

あなたは参照thisが、あなたは応答をログに記録しようとすることができラムダの

+0

dvの理由が分かりましたか?もしdvの男のためにありがとうございました –

+0

うわー、私はそれが同じだが異なるフォーマットだと思ったが、範囲のラムダ式に深い意味があるようだ。 –

+0

ありがとうございました! –

関連する問題