我有以下代码:
this.afDb.list('/demo').push({a: 'b'})
.then(_ => console.log('works'))
.catch(err => console.log('err: ', err));
我在'catch'上收到以下错误:
[ts] Property 'catch' does not exist on type 'PromiseLike<any>'.
好像是一个AngularFire2错误?
答案 0 :(得分:3)
报告错误是因为typescript中的PromiseLike
接口缺少catch
方法。这与“可以”作为具有then
方法的对象的定义一致。
interface PromiseLike { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike; }
是如何在gitHub上的lib.es2015.promise.d.ts中定义的,从第1291行开始。(链接的HTML页面大小为5.5MB - 可能需要一段时间。)
请记住,A5+ spec未提及catch
方法,而ES6(ECMAScript 2015)承诺提供catch
作为Promise.prototype
函数,只需调用then
catch
的第一个参数为then
的第二个参数。
最简单的解决方案可能是使用两个参数then
调用:
this.afDb.list('/demo').push({a: 'b'})
.then(_ => console.log('works'),
err => console.log('err: ', err));
或将Promise.prototype.catch
的代码扩展为then
来电:
this.afDb.list('/demo').push({a: 'b'})
.then(_ => console.log('works'))
.then( null, err => console.log('err: ', err)); // catch