【问题标题】:Ts Error : A function whose declared type is neither 'void' nor 'any' must return a value. when return statements are inside a subscribe methodTs 错误:声明类型既不是“void”也不是“any”的函数必须返回一个值。当返回语句在订阅方法中时
【发布时间】:2017-06-12 05:08:25
【问题描述】:

我在我的 Angular 2 项目中创建了一个简单的服务来检查用户是否登录。它检查用户对象是否存在于 FirebaseAuth 对象中。但是,当我的返回语句实际上在 auth 变量的 subscribe 方法中时,函数声明会为“缺少返回语句”引发错误。代码如下所示:

import { Component, OnInit , Injectable} from '@angular/core';
import { FirebaseAuthState, FirebaseAuth} from "angularfire2";
@Injectable()
export class CheckLogged {

constructor(private auth:FirebaseAuth ){}
check(): boolean{
    this.auth.subscribe((user: FirebaseAuthState) => {
        if (user) {
            return true;  
        }
        return false;
    })
  }
}

“check():boolean”语句抛出此错误

我在组件的 OnInit 生命周期钩子中调用我的函数 并将其分配给变量

this.loggedIn = this.CheckLogged.check();

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:
      check(): boolean{ // <<<== no boolean is returned from this function
        this.auth.subscribe((user: FirebaseAuthState) => {
            if (user) {
                return true;  
            }
            return false;
        })
      }
    

    在上面的代码中,return xxx 只从传递给subscribe(...) 的回调中返回,而不是从check 中返回。

    您无法从异步切换回同步。 该方法应该看起来像

      check(): Observable<boolean>{ // <<<== no boolean is returned from this function
        return this.auth.map((user: FirebaseAuthState) => {
            if (user) {
                return true;  
            }
            return false;
        })
      }
    

    然后调用者需要订阅返回值。

    【讨论】:

    • 工作就像一个魅力!非常感谢朋友。
    • 不客气。很高兴听到你能让它工作:)
    • 这给了我一个错误“地图不是函数”。我需要做相当于return this.auth.pipe(map( ....。不知道为什么,也许是为了避免与 EcmaScript map 冲突?见stackoverflow.com/questions/48668701/what-is-pipe-for-in-rxjs
    • 可能在 RxJS 6 中发生了变化。我自己还没有使用过。
    猜你喜欢
    • 2019-01-06
    • 2018-03-18
    • 2018-03-09
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    相关资源
    最近更新 更多