【发布时间】: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