使用 FirebaseListObservable 处理授权错误

Authorization Error handling with FirebaseListObservable

我正在尝试使用 catch 方法捕获来自 Firebase/AngularFire 的授权错误,但我收到错误 Property 'catch' does not exist on type 'FirebaseListObservable<any[]>'.

问题是我无法根据身份验证规则访问某些数据。当我通过身份验证时,代码可以工作(没有 .catch,因为这是一个编译错误)。

Records: FirebaseListObservable<any[]>;

constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase) 
{
    try {
        this.user = afAuth.authState;
        this.Records = af.list('/Testing');
    }
    catch (e) {
        console.log((<Error>e).message);//conversion to Error type
    }
}

以上方法可行。但是,如果 /Testing 由于身份验证规则而无法访问,则会出现异常。我似乎无法用标准 try/catch 捕获此错误。不过,我确实看到了使用 catch 的参考,

        this.Records = af.list('/Testing').catch(e => {
            console.log((<Error>e).message);//conversion to Error type
        });

然而,这给出了上面的编译错误。

虽然我知道我可以更改 Firebase 读取权限以允许任何人读取数据,但我正在尝试处理此错误情况以使我的代码更安全,以防有人访问应用程序的一部分正在尝试处理数据,但安全性不允许他们访问数据。

我不确定为什么 catch 不起作用,但您可以尝试这样的操作。 subscribe 的第二个参数是错误处理的参数,subscribe 必须存在于一个 observable 上。

af.list('/Testing').subscribe(()=>{}, (err)=>{console.log(err)})