我正在尝试为我的Angular应用创建一个登录功能。我使用的是Angular 4(它似乎与Angularjs不同)
我正试图弄清楚如何使用HTTP而我只是卡住了。
我在网页上收到此错误:
login.component.ts (29,3): Type 'Promise<User>' is not assignable to type 'User'.
Property 'id' is missing in type 'Promise<User>'.
这在控制台上:
login.component.ts (30,25): Property 'json' does not exist on type 'User'.
对于我的生活,我似乎无法从服务器发送实际的响应(见下文)。
我已经关注了angular.io(https://angular.io/tutorial/toh-pt6)上的HTTP教程,并且我尝试过.subscribe,.map等多种变体
这是访问后端的组件:
export class loginComponent {
SERVICE_URL = "http://localhost:80/play/classes/index.php?fn=userLogin";
model = new Login("", "");
user: User;
constructor(private http: Http) {}
onSubmit(){
console.log("submission complete!");
console.log(this.model.username);
console.log(this.model.pass);
let params: URLSearchParams = new URLSearchParams();
params.set('username', this.model.username);
params.set('password', this.model.pass);
this.user = this.doLogin(params);
console.log(this.user.json);
}
doLogin(params: URLSearchParams): Promise<User>{
return this.http.get(this.SERVICE_URL, new RequestOptions({"search": params}) )
.toPromise()
.then(response => response.json().data as User)
.catch(this.handleError);
}
get diagnostic() { return JSON.stringify(this.model); }
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
这是我从服务器获得的响应,但实际上无法在应用中使用:
{"id":"3","username":"jamiemac262","password":"123456","dob":"1993-03-24","email":"jamiemac262@xxxx.co.uk","steamID":null,"age":24}
答案 0 :(得分:1)
您没有解决访问数据的承诺
this.doLogin(params).then((data=>console.log(data));
使用then
运算符获取数据
更新你没有使用json映射并分离observable和promise
doLogin(params: URLSearchParams): Promise<User>{
let promise = this.http.get(this.SERVICE_URL, new RequestOptions({"search": params}) )
.map(response => <User>response.json())
.catch(this.handleError);
return promise.toPromise();
}
this.doLogin(params).then((data)=>console.log(data),()=>{});