【问题标题】:Angular 2 Service using Fetch and Promise使用 Fetch 和 Promise 的 Angular 2 服务
【发布时间】:2016-04-13 19:31:25
【问题描述】:

我正在运行 Angular 2 测试版。

我正在尝试使用实现承诺的 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 服务。
这就是我对技术的理解:

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

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

当我运行这个 Promise 时,响应为 null 或未定义。

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

【问题讨论】:

    标签: typescript promise angular fetch


    【解决方案1】:

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

    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() 中。

    【讨论】:

    • 你的最后一句话可能是我正在寻找的答案。 Angular 2 参考这里有一个过于简化的服务实现:angular.io/docs/ts/latest/tutorial/… 该示例实现了一个 Promise,但该示例没有使用 Web 服务作为示例。它让我相信我需要实现一个 Promise。因为 fetch API 已经提供了一个 promise,我不需要再实现一个了!!我会采纳您的建议,也不会将响应存储在服务中。再次感谢!
    • @LargeDachshund 请记住fetch() 不适用于所有浏览器。
    • 珊珊,感谢您的提醒。那么,您建议使用 Angular 2 内置的“http”吗?
    • @LargeDachshund 我不熟悉 Angular2(仅使用 v1),但我认为它更好。 Http 应该可以在任何浏览器上工作,而且它会返回一个 Observable,这似乎比 Angular2 环境中的 Promise 有趣得多。一个很好的阅读:chariotsolutions.com/blog/post/…
    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多