2017-08-20 36 views
0

調用接收憑據並檢索用戶的Rest服務。正在執行 HTTP方法不錯,但用戶對象不被更新,並且我不能其綁定到視圖:Angular2綁定無法使用Observable

用戶服務(連接到休息服務):

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

    } 
} 

控制檯

角是在開發模式下運行。調用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

可以嘗試登錄的反應如何? –

+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")); 

您使用的是function()語法參考this是無法訪問。嘗試使用lambda的

+0

DV的任何理由表示讚賞?如果不是謝謝dv的人 –

+0

哇,我認爲它是相同但不同的格式,但似乎有更深層次的範圍上的lambda表達式的意義。 –

+0

非常感謝,修好了! –

相關問題