使用Fetch和Promise的Angular 2服务

时间:2016-01-09 00:57:34

标签: typescript promise angular fetch

我正在运行Angular 2 beta。

我正在尝试使用实现promises的fetch创建一个http服务。这是我到目前为止所做的:

HttpService.ts:

@Injectable()
export class HTTPService {

    save(url: string, jsonPayload: JsonPayload): any {

        window.fetch(url, {
            method: "POST",
            headers: {
                       "Accept": "application/json",
                       "Content-Type": "application/json"
            },
            body: jsonPayload 
        })
        .then(status)
        .then(json)
        .then((response: any) => {
           this.response = response;

           return Promise.resolve(this.response);
        })
        .catch((error) => {
           console.log(error.message);

           return error.message;
        });
    }
}

这是服务消费类:

export class ConsumingComponent {
    constructor(private _httpService: HTTPService) {
               ...
    }

    getSampleStuff() {
        this._httpService
            .save("http:sample.com/sample/stuff", this.jsonPayload)
            .then(response => this.response = response);

        this.sampleStuffModel = this.response;
    }
}

我打算异步调用Web服务。
这就是我理解这项技术的方式:

  • 在服务中初始化承诺
  • 将服务注入消费类
  • 在消费类中添加“.then(...)”。回调结果落在这里。

我尝试将一个类成员(“this.response”)设置为响应(“响应”)。

当我运行此承诺时,响应为null或未定义。

我猜测解析函数的实现是问题的根源。我是否将整个window.fetch()包装在resolve()?

1 个答案:

答案 0 :(得分:2)

使用promises时,返回的值不会在所有链中冒泡。

window.fetch(...)
  .then(status) // only status function will have the response
  .then(json)

也许我错了,但statusjson似乎不是功能。你想在这做什么?

您的服务代码无法按预期恢复工作(我还删除了statusjson):

@Injectable()
export class HTTPService {
    save(url: string, jsonPayload: JsonPayload): any {
        // if you don't return anything, how the consumer will know it's a promise?
        return window.fetch(url, {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
            },
            body: jsonPayload
        })
        // do you really need to store the response into the service?
        // .then((response: any) => {
        //    this.response = response;
        //    return Promise.resolve(this.response);
        // })
        .catch((error) => {
            console.log(error.message);
            // if you return error.message here, the consumer won't know there is a problem
            // you need to rethrow the error so it can be catched by the consumer
            throw error;
        });
    }
}

windows.fetch()已经是一个承诺,请勿将其包含在resolve()