Angular 2 使用 Fetch 和 Promise 的服务

Angular 2 Service using Fetch and Promise

我是 运行宁 Angular 2 测试版。

我正在尝试使用实现承诺的提取创建一个 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;
        });
    }
}

这是服务消耗class:

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 服务。
我是这样理解技术的:

我尝试将 class 成员 ("this.response") 设置为响应 ("response")。

当我运行这个承诺时,响应为空或未定义。

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

使用 promises 时,返回值不会在整个链中冒泡。

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

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

您的服务代码缺少 return 无法按预期工作(我还删除了 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().

包装它