在这里,这是我的观察:
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"
}
答案 0 :(得分:3)
返回类型userLogin方法应为Observable<T>
,此处T代表您的响应数据类型/接口。您可以使用响应数据模型创建一个接口,并将其用作数据类型。
interface UserInterface {
pappassword: string
success: boolean
uamip: string
uamport: string
username: string
userurl: string
}
在你的userLogin方法中:
userLogin(formData: Object):Observable<UserInterface> {
...
}
我们可以使用Observable<any>
,但这是使用TypeScript的最佳做法。
答案 1 :(得分: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)}
);