2017-02-07 26 views
0

在这里,这是我观察到:可观察认购,则返回响应,无法访问域

userLogin(formData: Object):Observable<Response> { 
    return this.http.post(apiURL + '/api/logon', formData) 
     .map((response: Response) => { 
      return response.json(); 
     } 
    }) 
} 

然后我订阅,因为这地方:

this.auth.userLogin(forData) 
    .subscribe((result) => { 
    console.log(result); // this logs the response from server object 
    // console.log(result.username) doesn't work WHY? 
    // Error: Property 'username' does not exist on type 'Response' 
    }) 

那我做错了吗?

编辑:

CONSOLE.LOG输出该:

Object { 
    pappassword:"2f636cc3f8ffeda00dfe448fc483ce3" 
    success:true 
    uamip:"192.168.182.1" 
    uamport:"3990" 
    username:"jh" 
    userurl: "http://www.gstatic.com/generate_20" 
} 

enter image description here

+0

console.log(result)的输出是什么;?一切似乎都对我好。它可能只是一个类型错误,因为属性'result'实际上不存在于类型Response上。 –

+0

您正在从您的服务中返回Observable 。但是您应该返回Observable 或更好,然后创建您自己的数据模型并返回Observable (我相信称为Identity的模型适合您的情况)。 –

+0

@SabbirRahman用控制台响应更新了问题。 – Rexford

回答

2

返回类型USERLOGIN方法应该是Observable<T>,这里t为您的响应数据类型/接口。您可以使用响应数据模型创建一个接口,并将其用作数据类型。

interface UserInterface { 
    pappassword: string 
    success: boolean 
    uamip: string 
    uamport: string 
    username: string 
    userurl: string 
} 

而在你的用户登陆方法:

userLogin(formData: Object):Observable<UserInterface> { 
    ... 
} 

我们可以只使用Observable<any>但这是打字稿的最佳实践。

0
export class UserPayload{ 
constructor(public pappassword: string, 
      public success: boolean, 
      public uamip: string, 
      public uamport: string, 
      public username: string, 
      public userurl: string){}//using ts shorthand for properties in constructor 
} 

userLogin(formData: Object):Observable<UserPayload> { 
return this.http.post(apiURL + '/api/logon', formData) 
    .map((response: UserPayload) => { 
     return response.json(); 
    }).catch((error:any)=> Observable.throw(error.json() || 'Server Error')); 
} 

this.auth.userLogin(forData) 
    .subscribe((result) => { 
    console.log(result); // this logs the response from server object 
    console.log(result.username); //this should work now 
}, 
e=>{console.log(e)} 
);