Angular2处理组件中的http post promise

时间:2016-10-13 14:14:23

标签: angular http-post angular-promise

棱角分明的新人......

我创建了一个登录服务:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Request } from '../model/request';
import { ApiResponse } from '../model/apiresponse';
import { UserCredentials } from '../model/user';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Rx'


@Injectable()
export class LoginService {
private request = new Request();
constructor(private http: Http, _router: Router) { }

login(userCredentials:UserCredentials): Promise<ApiResponse> {
    console.log("requesting login")
    this.request.ServiceType = "Connect"
    this.request.SessionId = "sessionlessrequest"
    this.request.Compression = "no"
    this.request.Parameters = userCredentials;
    let jsonrequest = JSON.stringify(this.request)
    return this.http.post("http://localhost/request.php", "data="+ jsonrequest,
        { headers: new Headers({
            'Content-Type': 'application/x-www-form-urlencoded'
        })
    }).toPromise()
    .then(response => response.json())
}



logout() {

}

}

从我的登录组件调用此服务

import {Component} from '@angular/core';
import {LoginService} from '../shared/login.service';
import { UserCredentials } from '../model/user';
import { ApiResponse } from '../model/apiresponse';

@Component({
selector: 'login',
templateUrl: './app/login/login.component.html',
providers: [LoginService, UserCredentials]
})

export class LoginComponent {
public usercredentials = new UserCredentials();
public apiResponse:ApiResponse
constructor(private loginService:LoginService, userCredentials:UserCredentials) {
}
login(): void {
    console.log(this.usercredentials)
    //let apiResponse = this.loginService.login(this.usercredentials)
    this.loginService.login(this.usercredentials).then(apiResponse => this.apiResponse = apiResponse)
    //let response = apiResponse as ApiResponse
    console.log(this.apiResponse)
    console.log()

}
}

我不了解如何处理/访问组件中http post服务返回的数据。 我在chrome调试器的响应预览中看到它实际上返回了预期的数据。

预览google chrome调试器:

{Error: false, ErrorMessage: null, Data: {SessionId: "dgm6k7l1u763n26578k22rjot1",…}}
Data
:
{SessionId: "dgm6k7l1u763n26578k22rjot1",…}
Error
:
false
ErrorMessage
:
null

有人可以指导我吗?

...谢谢

更新

我现在写了以下代码:

login(): void {
        console.log(this.usercredentials)
 this.apiResponse = apiResponse; console.log(this.apiResponse);})
    this.loginService.login(this.usercredentials).then(apiResponse => { this.apiResponse = apiResponse;  
        if (!this.apiResponse.Error) {
            console.log("user logged in")
        } else {
            console.log(this.apiResponse.ErrorMessage)
        }
    })
}

这似乎有效。 是应该在服务中还是在组件中进行错误处理?

0 个答案:

没有答案