如何使用打字稿处理 Angular JS 服务中的响应和错误

How to handle response & error in Angular JS service with typescript

我正在使用 angular js 调用我的 returns 一些数据的 wcf 服务。现在,如果我的 wcf 服务抛出异常,我想相应地处理它。 我在angular的通话流程是这样的: 我的页面控制器调用 angular 服务,该服务使用 $http 调用我的 wcf 服务。 我的控制器:

setProfileStatus: (status: boolean) => 
{
 angularService.setProfileStatus(status).then(
response => {
     //my response is always undefined.
     console.log(response.data);         
  })
.catch(err => {
       //show error
}); 
}

在我上面的控制器中,当我调用我的服务时,我的响应总是未定义的。 这是我的服务:

public setProfileStatus(status: boolean): ng.IPromise<any> {
 var url = this._endpoints.myEndpoint + '?status=' + status;
 return this._http.put<string>(url, '').then(response => {
//response here is fine, I can get data also and any error but I want to pass this to my controller
 });
}

在我上面的服务调用中,我可以获得很好的响应,其中包含从我的 wcf 服务返回的任何数据。 那么如何将它传递给我的控制器,以便我可以在我的控制器中看到相同的响应。

谢谢

尝试获取大部分 IQservice

export class CaseFieldService {
    // Inject `ng.IQservice` to your `ProfileService`
    constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
    }

    public setProfileStatus(status: boolean): ng.IPromise<any> {
        // Create deferred 
        var d = this.$q.defer();            

        // resolve promise on success
        this.$http.put<string>(url, '')
            .success(response => d.resolve(response))
            .error(err => d.reject(err));

        // return promise
        return d.promise;
    }
}

在您的控制器方法中使用服务并添加 then:

private saveProfile(): void {

    this._profileService.setProfileStatus(true)
        .then(
               (result: any) => {
                  // success: use result value here
               }, 
               (error: any) => {
                   // error: handle error here
               }
    });
}